问题
One of my functions return a list of dataframes which I need to concatenate into 1 single dataframe. I do this using:
do.call(rbind,list_df)
This used to work as expected. But for some strange reason (which is driving me nuts!) it no longer does. Now, instead of combining into a single df, it just retains it as separate lists. When I print the output this is what I get (the list had 2 dataframes with 5 columns each, and the output is retained as such without concatenation)
out_df
[1,] List,5
[2,] List,5
Even when i try this manually without do.call (as shown below) it still gives me the same output, without concatenation:
rbind(list_df[[1]],list_df[[2]])
I am at a loss trying to figure out what's happening. (Each dataframe in the list has the same attributes - similiar no. of columns and same names, so rbind'ing should ideally work)
回答1:
From the output of "out_df", it looks like a nested list
. We could try
out <- do.call(rbind, do.call(c, list_df))
str(out)
# 'data.frame': 10 obs. of 5 variables:
# $ v1: int 1 2 3 4 5 1 2 3 4 5
# $ v2: int 6 7 8 9 10 6 7 8 9 10
# $ v3: int 11 12 13 14 15 11 12 13 14 15
# $ v4: int 16 17 18 19 20 16 17 18 19 20
# $ v5: int 21 22 23 24 25 21 22 23 24 25
data
list_df <- lapply(1:2, function(i) list(data.frame(v1=1:5,
v2= 6:10, v3= 11:15, v4 = 16:20, v5= 21:25)))
Using the OP's code,
do.call(rbind, list_df)
# [,1]
#[1,] List,5
#[2,] List,5
来源:https://stackoverflow.com/questions/34249266/rbind-dataframes-from-a-list