我有一个数据框,我希望用新名称替换列的子集,这些新名称是通过在旧文件名前添加标识符来创建的。例如,要在列3:7前加上字符串" TEST",我尝试了以下内容。
我在这里缺少什么?
# Make a test df
df <- data.frame(replicate(10,sample(0:1,100,rep=TRUE)))
#Subsetting works fine
colnames(df[,3:7])
#sub works fine
sub("^", "TEST.", colnames(df[,3:7]))
#replacing the subset of column names with sub does not
colnames(df[,3:7]) <- sub("^", "TEST.", colnames(df[,3:7]))
colnames(df)
#Also doesn't work
colnames(df[,3:7]) <- paste("TEST.", colnames(df[,3:7]), sep ="")
colnames(df)
答案 0 :(得分:3)
列名应该是一个向量,其中索引在括号外:
colnames(df)[3:7] <- sub("^", "TEST.", colnames(df)[3:7])
你也可以:
colnames(df)[3:7] <- paste0("TEST.", colnames(df)[3:7])