Modifying a specific part of the name of a DT in R

27 views Asked by At

I have the following DT

structure(list(HKU47_PSG_1_HW_0.txt = 66611.1718226969, HKU47_PSG_1_HW_1.txt = 66254.5524579138, 
    HKU47_PSG_1_HW_2.txt = 66972.3593176305, HKU47_PSG_1_HW_3.txt = 68419.8681965619, 
    HKU47_PSG_1_HW_4.txt = 66841.3761239946, HKU47_PSG_1_HW_5.txt = 66196.5383069813), .Names = c("HKU47_PSG_1_HW_0.txt", 
"HKU47_PSG_1_HW_1.txt", "HKU47_PSG_1_HW_2.txt", "HKU47_PSG_1_HW_3.txt", 
"HKU47_PSG_1_HW_4.txt", "HKU47_PSG_1_HW_5.txt"), row.names = c(NA, 
-1L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x0000000000100788>)

and I would like to have a clone of this DT cancelling from each column name this part of text HW_ and .txt. I would need something like names(data) <- c("new_name", "another_new_name") which works automatically for several DT I have. I do not have actually a clear idea how to do that.

1

There are 1 answers

0
janos On BEST ANSWER

You can use sub to replace HW_ with empty string, and replace .txt with empty string, effectively removing those parts from the names:

names(data) <- sub('HW_', '', sub('\\.txt', '', names(data)))