1

Suppose I have a list of different sized vectors that look like this:

> test
[[1]]
[1] 1

[[2]]
[1] 1 2 3 4

[[3]]
[1]  1  2  3  4  5  6  7 

What would be the best way to transform this into a data.frame with each list element as a column, while filling in missing rows with NA like so?

> test2
  V1 V2 V3
1  1  1  1
2 NA  2  2
3 NA  3  3
4 NA  4  4
5 NA NA  5
6 NA NA  6
7 NA NA  7

When I run do.call(cbind.fill,test), I get this:

  V1 V1 V1
1  1  1  1
2  1  2  2
3  1  3  3
4  1  4  4
5  1  1  5
6  1  2  6
7  1  3  7

Trying suggestion:

> do.call(rbind.data.frame, test)
  c.1L..1L..1L. c.1L..2L..2L. c.1L..3L..3L. c.1L..1L..4L. c.1L..2L..5L. c.1L..3L..6L. c.1L..1L..7L.
1             1             1             1             1             1             1             1
2             1             2             3             1             2             3             1
3             1             2             3             4             5             6             7
alki
  • 3,334
  • 5
  • 22
  • 45

2 Answers2

1

This will work:

test<-list(c(1),c(1:4),c(1:7))
library(qpcR)
do.call(qpcR:::cbind.na,test)
Andrelrms
  • 819
  • 9
  • 13
1

A base R solution would be:

test <- list(1,1:4,1:7)

do.call(cbind,lapply(test, `[`, 1:7))

or dynamically:

m <- max(sapply(test, length))
do.call(cbind,lapply(test, `[`, 1:m))
Rentrop
  • 20,979
  • 10
  • 72
  • 100