2016-02-19 30 views
0

我正在遍歷數據框列表dfList,它們都是Nx2,我想將每個數據幀的列名更改爲c("Date", dfList[i])。例如:爲可變數據幀分配可變列名稱

dfList <- c("df1", "df2", "df3") 

for(i in 1:length(dfList)){ 
    names(get(dfList[i])) <- c("Date", dfList[i]) 
} 

這將導致錯誤:

Error in names(get(dfList[i])) <- c("Date", dfList[i]) : could not find function "get<-"

names(get(dfList[i]))本身的工作原理,並返回原來的列名。另外,c("Date", dfList[i])的作品。

任何想法如何解決我收到的錯誤?

謝謝!

回答

1

嘗試:

for(i in 1:length(dfList)){ 
    temp <- get(dfList[i]) 
    names(temp) <- c("Date", dfList[i]) 
    assign(dfList[i],temp) 
} 

應當注意的是,你應儘量避免getassign,而且它可能更好,當你創建的數據幀指定的列名。

0

如果你確定使用purrr:

library(purrr) 

df_list <- list(data.frame(1:10, ncol = 2), 
       data.frame(1:20, ncol = 2), 
       data.frame(1:30, ncol = 2)) 


map2(df_list, 1:length(df_list), function(x, y) setNames(x, c("Date", paste('df', y, sep = ""))))