我正在使用约10个数据集,并且需要更改列名称以匹配所有这些名称,每个数据集包含相同数量的列。目前,这就是我正在做的事情,但是我知道必须有一种更简洁的输入方式。
第1周到第10周是我正在使用的数据集。
colnames(week1) <- c("Itemsinfolder", "Foldersize (KB)", "Foldersubfoldersize (KB)", "User", "Level1folder", "Level2folder", "Level3folder", "Level4folder", "Level5folder")
colnames(week2) <- c("Itemsinfolder", "Foldersize (KB)", "Foldersubfoldersize (KB)", "User", "Level1folder", "Level2folder", "Level3folder", "Level4folder", "Level5folder")
colnames(week3) <- c("Itemsinfolder", "Foldersize (KB)", "Foldersubfoldersize (KB)", "User", "Level1folder", "Level2folder", "Level3folder", "Level4folder", "Level5folder")
colnames(week4) <- c("Itemsinfolder", "Foldersize (KB)", "Foldersubfoldersize (KB)", "User", "Level1folder", "Level2folder", "Level3folder", "Level4folder", "Level5folder")
等到第10周
谢谢
答案 0 :(得分:0)
我们可以通过将数据集保存在list
中并使用首选名称('vec')vector
更改列名称来立即执行此操作。如果需要在全局环境中更改对象,请使用list2env
(尽管最好将其保留在list
中)
lst <- lapply(mget(paste0("week", 1:10)), setNames, vec)
list2env(lst, envir = .GlobalEnv)
另一个选项是assign
循环中的for
wks <- paste0("week", 1:10)
for(wk in wks) assign(wk, `names<-`(get(wk), vec))
使用可复制的示例
week1 <- data.frame(col1 = 1:5, col2 = 6:10)
set.seed(24)
week2 <- data.frame(col1 = rnorm(5), col2 = rnorm(5))
wks <- paste0('week', 1:2)
vec <- paste0("V", 1:2)
for(wk in wks) assign(wk, `names<-`(get(wk), vec))
vec <- c("Itemsinfolder", "Foldersize (KB)", "Foldersubfoldersize (KB)", "User",
"Level1folder", "Level2folder", "Level3folder", "Level4folder", "Level5folder")