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

William Dunlap wdunlap at tibco.com
Wed Jan 11 21:47:08 CET 2012


Perhaps the following does what you want.  It extends
each element of your list to a common length, converts
that to a matrix, then to a data.frame:

  f <- function(data) {
    nCol <- max(vapply(data, length, 0))
    data <- lapply(data, function(row) c(row, rep(NA, nCol-length(row))))
    data <- matrix(unlist(data), nrow=length(data), ncol=nCol, byrow=TRUE)
    data.frame(data)
  }
E.g.,
  > rawData <- list(c(1,2,3), c(11,12), integer(), 31)
  > f(rawData)
    X1 X2 X3
  1  1  2  3
  2 11 12 NA
  3 NA NA NA
  4 31 NA NA

What sort of data is this?  If it is longitudinal
it might be more straigtforward to store it as a
three-column data.frame (columns "subject", "time", "value").

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Chris Conner
> Sent: Wednesday, January 11, 2012 11:41 AM
> To: HelpR
> Subject: [R] turning a list of vectors into a data.frame (as rows of the DF)?
> 
> 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]]



More information about the R-help mailing list