user1172468 user1172468 - 3 months ago 26
R Question

How do I cbind elements of a list that are data.frame of the same row size into one large data.frame

Say I have a list which have 4 data frames

l<-list()
l[[1]]<-data.frame(1:10)
l[[2]]<-data.frame(runif(10))
l[[3]]<-data.frame(rnorm(10))
l[[4]]<-data.frame(10:1)


how do I cbind these into one data.frame?

When I try cbind I get:

> cbind(l)
l
[1,] List,1
[2,] List,1
[3,] List,1
[4,] List,1

Answer

What we need is not cbind(l), but cbind(l[[1]], l[[2]], l[[3]], l[[4]]). In R, we can use do.call() to achieve this:

do.call(cbind, l)

#   X1.10  runif.10.  rnorm.10. X10.1
#1      1 0.40645551  0.7672801    10
#2      2 0.47996864 -0.2556100     9
#3      3 0.87533193 -0.5907474     8
#4      4 0.38525509 -0.9637239     7
#5      5 0.63586646 -0.2042599     6
#6      6 0.35743512 -0.7991810     5
#7      7 0.73211818 -0.7801925     4
#8      8 0.72659327  0.4355651     3
#9      9 0.11137715 -0.4393534     2
#10    10 0.08484517  0.4154295     1

For you specific problem, you can also use

as.data.frame(l)
Comments