Combining dataframes into a list

六眼飞鱼酱① 提交于 2021-02-10 07:57:16

问题


I'm trying to store multiple dataframes in a list. However, at some point, the dataframes end up getting converted into lists, and so I end up with a list of lists.

All I'm really trying to do is keep all my dataframes together in some sort of structure.

Here's the code that fails:

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
}

If I now call, for example, class(all_dframes[1]), I get 'list', whereas if I call class(dframe) I get 'data.frame'!


回答1:


Of course, the class of all_dframes[1] is list since all_dframes is a list. The function [ returns a subset of the list. In this example, the length of the returned list is one. If you want to extract the data frame you have to use [[, i.e., all_dframes[[1]].




回答2:


May I suggest this:

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

Is this what you need?



来源:https://stackoverflow.com/questions/26730970/combining-dataframes-into-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!