Reputation: 5690
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'!
Upvotes: 2
Views: 229
Reputation: 3297
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?
Upvotes: 1
Reputation: 81683
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]]
.
Upvotes: 4