0

I have a list of evenly sized characters vectors, and I wish to efficiently combine them into one dataframe, with the vectors in the list to become the rows of the new dataframe. In the following, ls is my list and df is my pre-allocated dataframe.

ls <- list(c("r1c1", "r1c2", "r1c3"),
           c("r2c1", "r2c2", "r2c3"))

df <- data.frame(col1 = character(), col2 = character(), col3 = character(),
                 stringsAsFactors = F)

# Desired Result:
  col1   col2   col3
1  r1c1   r1c2   r1c3       
2  r2c1   r2c2   r2c3  

As of now, I've tried rbind(df, ls) which seemingly creates the new dataframe by column, such that df looks like:

  c..r1c1....r1c2....r1c3.. c..r2c1....r2c2....r2c3..
4                      r1c1                      r2c1
5                      r1c2                      r2c2
6                      r1c3                      r2c3

I've also tried to perform the rbind inside of a for loop:

for (i in 1:length(ls))
  df <- rbind(df, ls[[i]])

This, however, gives me the warning message: invalid factor level, NA generated, even though I originally set stringsAsFactors to false. Rbind also seems to be a slow process when constantly performed on larger lists, so I would like to minimize its use if possible.

Any help would be greatly appreciated.

Arun
  • 116,683
  • 26
  • 284
  • 387
Evan Kaminsky
  • 695
  • 10
  • 23

1 Answers1

8

You could use

 data.frame(do.call(rbind, ls))

as a quick and simple way to turn your list of vectors into a matrix and then a data.frame

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • 3
    This will be pretty slow on anything remotely large. If you do `L <- do.call(Map,c(c,listname))` and then this method: http://stackoverflow.com/a/18748069/496803 it will be much quicker. – thelatemail Jul 28 '14 at 05:48