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.
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"
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