使用加载到List中的数据帧的for循环更改多个数据帧的列名

时间:2018-04-05 15:37:13

标签: r list for-loop dataframe iteration

我正在尝试更改for循环中所有数据框中的变量名称。任何数据示例都是:

df1 <- data.frame(
  Number = c(45,62,27,34,37,55,40),
  Day = c("Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun"))
df2 <- data.frame(
  Number = c(15,20,32,21,17,18,13),
  Day = c("Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun"))
df3 <- data.frame(
  Number = c(12,32,22,14,16,21,30),
  Day = c("Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun")

L <- list(df1,df2,df3)

我目前的尝试是:

for(i in L){
colnames(L) <- c("NewName1", "NewName2")
}

哪个不起作用,我不明白为什么它不起作用。如果有人能指导我正确的方向,请告诉我。

1 个答案:

答案 0 :(得分:4)

L <- lapply(L, function(x){
  colnames(x) <- c("NewName1", "NewName2")
  x
} )