2017-08-24 36 views
1

假設我有一個數據幀(DF),看起來像以下:同時改變R基團數據幀列名

test <- c('Test1','Test2','Test3') 
col.DF.names < c('ID', 'year', 'car', 'age', 'year.1', 'car.1', 'age.1', 'year.2', 'car.2', 'age.2') 

ID <- c('A','B','C') 

year <- c(2001,2002,2003) 
car <- c('acura','benz','lexus') 
age <- c(55,16,20) 

year.1 <- c(2011,2012,2013) 
car.1 <- c('honda','gm','bmw') 
age.1 <- c(43,21,34) 

year.2 <- c(1961,1962,1963) 
car.2 <- c('toyota','porsche','jeep') 
age.2 <- c(33,56,42) 

DF <- data.frame(ID, year, car, age, year.1, car.1, age.1, year.2, car.2, age.2) 

我需要的數據幀的列失去了「#」和而不是在它前面的測試#,所以它看起來是這樣的:

ID Test1.year Test1.car Test1.age Test2.year Test2.car Test2.age Test3.year Test3.car Test3.age 
.... with all the data 

有沒有人有一個建議?基本上,從第二列開始,我想爲3列添加測試[1]名稱,然後移動到下一組三列並添加測試[2]依此類推。

我知道如何硬編碼:

colnames(DF)[2:4] <- paste(test[1], colnames(DF)[2:4], sep = ".") 

但這是一個玩具一套,我想有點自動化,所以我沒有具體說明[2:4]。例如

回答

1

您可以嘗試:

colnames(DF)[-1] <- paste(sapply(test, rep, 3), colnames(DF)[-1], sep = ".")

或許下面會更好:

colnames(DF)[-1] <- paste(sapply(test, rep, 3), colnames(DF)[2:4], sep = ".")

或:

colnames(DF)[-1] <- paste(rep(test, each=3), colnames(DF)[2:4], sep = ".")

感謝@thelatemail

+0

謝謝!這非常有幫助!我現在如何去除一些列名中的.1和.2? – Sheila

+1

如果它們實際上是重複的,您可以重複使用前三列名稱,如我的第二個示例中所示。 – Mosquite

+3

'sapply'是不必要的。 'rep'具有'each ='參數 - 'paste(rep(test,each = 3),names(DF [2:4]),sep =「。」)'' – thelatemail