我想重命名所有列,除了我想要按名称指定的几个列。这里的问题是列在数据集之间的顺序不同,我想要一个通用代码。
#data is a list of the data.tables I want to rename
for (i in 1:length(data)) {
temp <- data[i]
setkeyv(get(temp), c("HDDSN","ENDDATE"))
#trying to create a list of all columns that are NOT named "some name"
orig.names <- which(names(get(temp))!=c("HDDSN","ENDDATE","PHEADNO"))
#I want to rename the columns in the format of "p+tablename+original names"
new.names <- paste(paste("p",substring(temp,5,13), sep=""), get(temp)[orig.names], sep=".")
setnames(get(temp), orig.names, new.names)
}
创建orig.names对象给我带来了麻烦。
答案 0 :(得分:0)
下面的代码怎么样?它允许您重命名列,而不必担心它在数据帧中的相对位置。您可以考虑在运行迭代重命名for-loop之后运行它。
names(dataframe)[names(dataframe)=="oldname"] <- "newname"