Can I combine a list of similar dataframes into a single dataframe?

There are several problems with your code.

The first is that the assignment statement in the list doesn't work. This needs to be fixed by, for example:

foo <- list(
        df1 = data.frame(x=c('a', 'b', 'c'), y = c(1,2,3)), 
        df2 = data.frame(x=c('d', 'e', 'f'), y = c(4,5,6))
)

You can then use rbind() to combine the data frames:

rbind(foo$df1, foo$df2)

  x y
1 a 1
2 b 2
3 c 3
4 d 4
5 e 5
6 f 6

But this poses more questions. For example, why do you combine the data frames in a list in the first place. The second is whether you really need to use data frames rather than vectors. Finally, I generally try to avoid rbind() and rather use merge() when combining data frames in this way.


with plyr:

foo <- list(df1 = data.frame(x=c('a', 'b', 'c'),y = c(1,2,3)), 
        df2 = data.frame(x=c('d', 'e', 'f'),y = c(4,5,6)))

library(plyr)
ldply(foo)[,-1]
  x y
1 a 1
2 b 2
3 c 3
4 d 4
5 e 5
6 f 6

How about merge(foo[[1]], foo[[2]], all = TRUE)


do.call("rbind", foo) should do the trick.

Tags:

List

R

Dataframe