I have a nested list like this:
nested_list <- list(a = c(1,2),
b = list(
c = c(3,4),
d = list(
e = c(5,6,7)
)))
I want to simplify it so it looks like this (only one level, nested names grouped using colons):
simplified_list <- list(a = c(1,2),
"b:c" = c(3,4),
"b:d:e" = c(5,6,7)
)
What's the best way to do this?
Remove items from a Nested List. If you know the index of the item you want, you can use pop() method. It modifies the list and returns the removed item. If you don't need the removed value, use the del statement.
Converting a List to Vector in R Language – unlist() Function. unlist() function in R Language is used to convert a list to vector. It simplifies to produce a vector by preserving all components.
This approach has the advatnage of being quite short. It does not use any packages. It assumes that the input names do not contain trailing digits:
u <- unlist(nested_list)
res <- tapply(u, sub("\\d+$", "", names(u)), unname)
giving:
> res
$a
[1] 1 2
$b.c
[1] 3 4
$b.d.e
[1] 5 6 7
If its important that the names be separated by : instead of . then add this:
names(res) <- chartr(".", ":", names(res))
I make no claims to "best", but this works:
d <- reshape2::melt(nested_list)
> d
value L3 L2 L1
1 1 <NA> <NA> a
2 2 <NA> <NA> a
3 3 <NA> c b
4 4 <NA> c b
5 5 e d b
6 6 e d b
7 7 e d b
> d$L <- apply(d[,c('L1','L2','L3')],1,function(x) paste(unique(x[!is.na(x)]),collapse = ":"))
> l <- plyr::dlply(d,"L",function(x) unlist(x$value))
> l
$a
[1] 1 2
$`b:c`
[1] 3 4
$`b:d:e`
[1] 5 6 7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With