Home:ALL Converter>How to simplify a nested list in R?

How to simplify a nested list in R?

Ask Time:2014-12-20T04:10:54         Author:nachocab

Json Formatter

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?

Author:nachocab,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/27573226/how-to-simplify-a-nested-list-in-r
G. Grothendieck :

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:\n\nu <- unlist(nested_list)\nres <- tapply(u, sub(\"\\\\d+$\", \"\", names(u)), unname)\n\n\ngiving:\n\n> res\n$a\n[1] 1 2\n\n$b.c\n[1] 3 4\n\n$b.d.e\n[1] 5 6 7\n\n\nIf its important that the names be separated by : instead of . then add this:\n\nnames(res) <- chartr(\".\", \":\", names(res))\n",
2014-12-19T21:36:55
joran :

I make no claims to \"best\", but this works:\n\nd <- reshape2::melt(nested_list)\n> d\n value L3 L2 L1\n1 1 <NA> <NA> a\n2 2 <NA> <NA> a\n3 3 <NA> c b\n4 4 <NA> c b\n5 5 e d b\n6 6 e d b\n7 7 e d b\n> d$L <- apply(d[,c('L1','L2','L3')],1,function(x) paste(unique(x[!is.na(x)]),collapse = \":\"))\n> l <- plyr::dlply(d,\"L\",function(x) unlist(x$value))\n> l\n$a\n[1] 1 2\n\n$`b:c`\n[1] 3 4\n\n$`b:d:e`\n[1] 5 6 7\n",
2014-12-19T20:34:36
rawr :

Another option:\n\nnested_list <- list(a = c(1,2),\n b = list(\n c = c(3,4),\n d = list(\n e = c(5,6,7)\n )))\n\n\nul <- unlist(nested_list)\nsp <- split(unname(ul), gsub('\\\\d', '', names(ul)))\n`names<-`(sp, gsub('\\\\.', ':', names(sp)))\n# $a\n# [1] 1 2\n# \n# $`b:c`\n# [1] 3 4\n# \n# $`b:d:e`\n# [1] 5 6 7\n",
2014-12-19T21:35:13
Stibu :

I was too slow, but maybe my solution still helps. It is somewhat longer than joran's, but (at least to me) seems easier to understand. (But maybe that is just because I'm not too familiar with the plyr package.) I definitely won't claim it's the best solution...\n\n# create names for the list\nnm <- names(unlist(nested_list))\nnm <- unique(sub(\"[0-9]*$\",\"\",nm))\nnm <- gsub(\"\\\\.\",\":\",nm)\n\n# construct list\nnew_list <- lapply(nm,function(n) {\n nested_list[[strsplit(n,\":\")[[1]]]]\n})\n\n# apply names\nnames(new_list) <- nm\n> new_list\n$a\n[1] 1 2\n\n$`b:c`\n[1] 3 4\n\n$`b:d:e`\n[1] 5 6 7\n",
2014-12-19T20:41:28
yy