[R] turning a list of vectors into a data.frame (as rows of the DF)?

Marc Schwartz marc_schwartz at me.com
Wed Jan 11 21:51:54 CET 2012

On Jan 11, 2012, at 1:40 PM, Chris Conner wrote:

> As a newer R practicioner, it seems I stump myself weekly (at least) with issues that have spinning my wheels.  Here is yet another... I'm trying to turn a list of numeric vectors (of uneual length) inot a dataframe.  Each vector held in the list represents a row, and there are some rows of unequal length.  I would like NAs as placeholders for "missing" data in the shorter vectors.  I think I'm missing something quite basic.
> v1 <- c(1,2,3,4)
> v2 <- c(1,2)
> lst1 <- list(v1,v2)
> Of course there is the intuitive:
> as.data.frame(lst1)
> However, the recycling rule (expectedly) reclycles 1,2 versus using NAs as placeholders.
> Then, looking into Teetor's R Cookbook, there is a piece of code that looked (from the description) like it might do the trick:
> do.call(rbind, Map(as.data.frame,lst1)
> But I get the error:
> Error in match.names(clabs, names(xi)) : 
>   names do not match previous names
> Thinking the source of the error had to do with the vectors of unequal lenght, I tried Hadley's rbind.fill thusly:
> library(reshape)
> do.call(rbind.fill, Map(as.data.frame,lst1)
> Which produced a dataset, but gain, not in the desired format.
> Thanks in advance to anyone that can bring my frustrations to end!
> C
> 	[[alternative HTML version deleted]]

There may be an easier way, but try this:

list2df <- function(x)
  MAX.LEN <- max(sapply(x, length), na.rm = TRUE)
  DF <- data.frame(lapply(x, function(x) c(x, rep(NA, MAX.LEN - length(x)))))
  colnames(DF) <- paste("V", seq(ncol(DF)), sep = "")  

> list2df(lst1)
  V1 V2
1  1  1
2  2  2
3  3 NA
4  4 NA


Marc Schwartz

More information about the R-help mailing list