Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simplify a nested list in R?

Tags:

list

r

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?

like image 479
nachocab Avatar asked Dec 19 '14 20:12

nachocab


People also ask

How do I remove items from my nested list?

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.

How do I unlist a list in R?

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.


2 Answers

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))
like image 65
G. Grothendieck Avatar answered Sep 23 '22 23:09

G. Grothendieck


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
like image 33
joran Avatar answered Sep 23 '22 23:09

joran