Buthetleon
Buthetleon

Reputation: 1305

recursively adding columns to a data.frame where values corresponds to vectors in a list

I have a list of vectors whose values are bounded between 1 and 100.

[[1]]
[[1]][[1]]
[1] "a"

[[1]][[2]]
[1] 41  5 53 55 56


[[2]]
[[2]][[1]]
[1] "b"

[[2]][[2]]
[1] 41 1 57 53  48

etc.

How do i somehow get to the following data.frame

  no      1        2
  1      NA        b
  41      a        b
   5      a       NA
  53      a       NA
  55      a       NA
  56      a       NA
  48     NA        b
  57     NA        b
  53     NA        b

and from there fill in the missing rows and ordered according to the column "no" where column no. runs from 1 to 100? eg.

  no      1        2
  1      NA        b
  2      NA       NA
  3      NA       NA
  4      NA       NA
  5      a        NA

etc. all the way until the 100th row.

Upvotes: 0

Views: 1659

Answers (2)

Sven Hohenstein
Sven Hohenstein

Reputation: 81733

Here is an approach with lapply:

The data:

dat <- list(list("a", c(41, 5, 53, 55, 56)), list("b", c(41, 1, 57, 53, 48)))

The solution:

lev <- 1:100                # the unique numbers
vec <- rep(NA, length(lev)) # a vector full of NAs

data.frame(no = lev,
           setNames(lapply(dat,
                           function(x) "[<-"(vec, lev %in% x[[2]], x[[1]])),
                    seq_along(dat)), check.names = FALSE)

The output (the first 10 rows):

     no    1    2
1     1 <NA>    b
2     2 <NA> <NA>
3     3 <NA> <NA>
4     4 <NA> <NA>
5     5    a <NA>
6     6 <NA> <NA>
7     7 <NA> <NA>
8     8 <NA> <NA>
9     9 <NA> <NA>
10   10 <NA> <NA>

Upvotes: 2

James
James

Reputation: 66874

For the first part, try this:

x <- list(list("a",c(41,5,53,55,56)),list("b",c(41,1,57,53,48)))

xl <- lapply(x,function(y) `names<-`(as.data.frame(y),c("chr","no")))

xm <- merge(xl[[1]],xl[[2]],by="no",all=T)
xm
  no chr.x chr.y
1  1  <NA>     b
2  5     a  <NA>
3 41     a     b
4 48  <NA>     b
5 53     a     b
6 55     a  <NA>
7 56     a  <NA>
8 57  <NA>     b

And for the second (I've not printed the output for brevity):

merge(data.frame(no=1:100),xm,all=T)

Upvotes: 2

Related Questions