2014-11-04 189 views
2

我试图在列表中存储多个数据帧。然而,在某些时候,数据框最终会被转换成列表,所以我最终列出了一个列表。将数据帧组合到列表中

我真的很想做的事情就是把所有的数据帧都保存在某种结构中。

下面是失败的代码:

all_dframes <- list() # initialise a list that will hold a dataframe as each item 
for(file in filelist){ # load each file 
    dframe <- read.csv(file) # read CSV file 
    all_dframes[length(all_dframes)+1] <- dframe # add to the list 
} 

如果我现在打电话,例如,class(all_dframes[1]),我得到的名单“,而如果我叫class(dframe)我得到“data.frame”!

+5

你可以完成'files < - list.files(pattern =“。csv”); lapply(files,function(x)read.csv(x,header = TRUE))' – akrun 2014-11-04 08:56:19

+1

或'library(data.table);文件< - lapply(list.files(pattern =“。csv”),fread)' – zx8754 2014-11-04 09:14:59

回答

4

当然,all_dframes[1]的等级是list,因为all_dframes是一个列表。功能[返回列表的一个子集。在这个例子中,返回列表的长度是1。如果你想提取数据帧,你必须使用[[,即all_dframes[[1]]

+0

Agk! R的'[]'/'[[]]'区别。讨厌它。谢谢Sven。 – Mars 2015-04-16 20:14:34

1

我建议这样的:

library(data.table) 
all_dframes <- vector("list",length(filelist)) 
for(i in 1:length(filelist)){ # load each file 
     all_dframes[[i]]<-fread(filelist[i]) 
} 

这是你需要什么?