Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a recursive list from a list of vectors

Tags:

r

recursion

Suppose I've got the following list, which represents a directory structure :

> pages <- list("about.Rmd", "index.Rmd", c("stats", "index.Rmd"), c("stats", "substats", "index.Rmd"))
> pages
[[1]]
[1] "about.Rmd"

[[2]]
[1] "index.Rmd"

[[3]]
[1] "stats"     "index.Rmd"

[[4]]
[1] "stats"     "substats"  "index.Rmd"

I'd like to create a recursive version of this list, something that would look like this :

> rpages <- list("about.Rmd", "index.Rmd", stats=list("index.Rmd", substats=list("index.Rmd")))
> rpages
[[1]]
[1] "about.Rmd"

[[2]]
[1] "index.Rmd"

$stats
$stats[[1]]
[1] "index.Rmd"

$stats$substats
$stats$substats[[1]]
[1] "index.Rmd"

I've tried different ways to do it, but I fear I'm now lost in a sea of lapply and sapply.

Thanks in advance for any hint.

like image 740
juba Avatar asked Mar 24 '15 15:03

juba


1 Answers

I think this does it:

build_list = function(item, res) {
  if (length(item) > 1) {
    res[[item[1]]] = build_list(tail(item, -1), res[[item[1]]])
  } else {
    res = c(res, list(item))
  }
  res
}

res = list()
for (i in seq_along(pages)) res = build_list(pages[[i]], res)

res
#[[1]]
#[1] "about.Rmd"
#
#[[2]]
#[1] "index.Rmd"
#
#$stats
#$stats[[1]]
#[1] "index.Rmd"
#
#$stats$substats
#$stats$substats[[1]]
#[1] "index.Rmd"
like image 155
eddi Avatar answered Oct 21 '22 09:10

eddi