[英]Create a recursive list from a list of vectors
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
. 我尝试过不同的方法,但我担心自己现在迷失在一片lapply
和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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.