Conversion of the list of lists into a data frame in R

advertisements

I am working with nested lists in R and am running into a problem with rbindlist. I have lists that look like this

L <- list(list(list(c(0,0)),list(c(0,0)),list(c(33,37))), list(list(c(0,0)),list(c(0,0)),list(c(29,33))))

Resulting in:

[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
[1] 0 0

[[1]][[2]]
[[1]][[2]][[1]]
[1] 0 0

[[1]][[3]]
[[1]][[3]][[1]]
[1] 33 37

[[2]]
[[2]][[1]]
[[2]][[1]][[1]]
[1] 0 0

[[2]][[2]]
[[2]][[2]][[1]]
[1] 0 0

[[2]][[3]]
[[2]][[3]][[1]]
[1] 29 33

What I am trying to do is collapse each sub-list into a data frame that would look something like this (this result is what I want from the first set of lists above):

config alpha start end
1        1     0    0
1        2     0    0
1        3     33   37
2        1     0    0
2        2     0    0
2        3     29   33

But some lists have a different number of sub-lists relative to the other lists in the sub-list. For example, a list like this (with 2 sub-lists in the middle instead of 3 1-sublist sub-lists).

L <- list(list(c(0,0)), list(c(1,4),c(5,9)), list(c(0,0)) )
[[1]]
[[1]][[1]]
[1] 0 0

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

[[2]][[2]]
[1] 5 9

[[3]]
[[3]][[1]]
[1] 0 0

when I try rbindlist I get this error:

> rbindlist(lapply(master_init, as.list))
Error in rbindlist(lapply(master_init, as.list)) :
  Column 2 of item 50 is length 2, inconsistent with first column of that item which is length 1. rbind/rbindlist doesn't recycle as it already expects each item to be a uniform list, data.frame or data.table

I know what the error means but not how to fix it. Thoughts?


While this isn't a complete answer, it may get you started on the right path.

L1 <- list(list(list(c(0,0)),list(c(0,0)),list(c(33,37))), list(list(c(0,0)),list(c(0,0)),list(c(29,33))))
L2 <- list(list(c(0,0)), list(c(1,4),c(5,9)), list(c(0,0)))

as.data.frame(matrix(unlist(L1), ncol = 2, byrow = TRUE))

  V1 V2
1  0  0
2  0  0
3 33 37
4  0  0
5  0  0
6 29 33

as.data.frame(matrix(unlist(L2), ncol = 2, byrow = TRUE))
  V1 V2
1  0  0
2  1  4
3  5  9
4  0  0