Given a nested list, how to create all possible lists from its elements, while preserving the structure of the nested list?
Nested list:
The relist
function from utils
seems to be designed for this task:
rl <- as.relistable(l)
r <- expand.grid(data.frame(rl), KEEP.OUT.ATTRS = F)
> head(r, 5)
b c.d.e c.d.f g
1 1 3 5 7
2 2 3 5 7
3 1 4 5 7
4 2 4 5 7
5 1 3 6 7
It saves the structure of the list (skeleton
). This means one can now manipulate the data within the nested list and re-assign it into the structure (flesh
). Here with the first row of the expanded matrix.
r <- rep(unname(unlist(r[1,])),each = 2)
l2 <- relist(r, skeleton = rl)
> l2
$a
$a$b
[1] 1 1
$c
$c$d
$c$d$e
[1] 3 3
$c$d$f
[1] 5 5
$g
[1] 7
attr(,"class")
[1] "relistable" "list"
Note that since the structure stays the same, I need to supply the same amount of elements as in the original list. This is why used rep
to repeat the element twice. One could also fill it with NA
, I guess.
For every possible combination iterate through r
(expanded):
lapply(1:nrow(r), function(x)
relist(rep(unname(unlist(r[x,])),each = 2), skeleton = rl))