我在寻找一个简单的方法来创建基于包括命名向量或列表的“平”或凝结名称结构的嵌套列表
例如,输入c("a/b/c" = TRUE)
应导致:
#> $a
#> $a$b
#> $a$b$c
#> [1] TRUE
我有一个解决方案,但感觉还涉及:
library(magrittr)
nested_list <- function(input) {
nms <- names(input)
ret <- lapply(1:length(input), function(level) {
value <- input[[level]]
name <- nms[level] %>%
strsplit("/") %>%
unlist()
name_vec <- NULL
ret <- list()
# Create nested list structure -----
for (ii in name) {
name_vec <- c(name_vec, ii)
ret[[name_vec]] <- list()
}
# Assign leaf value -----
ret[[name]] <- value
ret
})
unlist(ret, recursive = FALSE)
}
示例运行
input <- c("a/b/c" = TRUE, "x/y/z" = FALSE)
nested_list(input)
#> $a
#> $a$b
#> $a$b$c
#> [1] TRUE
#>
#>
#>
#> $x
#> $x$y
#> $x$y$z
#> [1] FALSE
input <- list("a/b/c" = TRUE, "x/y/z" = list(p = 1, q = 2))
nested_list(input)
#> $a
#> $a$b
#> $a$b$c
#> [1] TRUE
#>
#>
#>
#> $x
#> $x$y
#> $x$y$z
#> $x$y$z$p
#> [1] 1
#>
#> $x$y$z$q
#> [1] 2
Created on 2018-10-18 by the [reprex package][1] (v0.2.0).
我也环顾了一下(例如question 1,question 2),但我并没有完全找到了我一直在寻找。
我写了一个递归函数,它有类似的功能
recur.list <- function(x, y) {
if(length(x) == 1)
setNames(list(y), x[1])
else
setNames(list(recur.list(x[-1], y)), x[1])
}
listed_list.dirs <- function(input) {
vec <- strsplit(names(input), "/")
mapply(recur.list, vec, input)
}
基本上recur.list
是其产生基于所述数目命名嵌套列表的递归函数“/”而分裂listed_list.dirs
上“/”的名称和创建的字符为每个input
的分开的载体。
input <- c("a/b/c" = TRUE, "x/y/z" = FALSE)
listed_list.dirs(input)
#$a
#$a$b
#$a$b$c
#[1] TRUE
#$x
#$x$y
#$x$y$z
#[1] FALSE
input <- list("a/b/c" = TRUE, "x/y/z" = list(p = 1, q = 2))
listed_list.dirs(input)
#$a
#$a$b
#$a$b$c
#[1] TRUE
#$x
#$x$y
#$x$y$z
#$x$y$z$p
#[1] 1
#$x$y$z$q
#[1] 2