基于命名矢量或列表的平面/压缩名称结构的嵌套列表 [英] Nested list based on flat/condensed name structure of named vector or list
问题描述
我正在寻找一种简单的方法来创建基于命名矢量或列表的平面"或压缩名称结构的嵌套列表
I'm looking for a simple way to create a nested list based on a "flat" or condensed name structure of either a named vector or a list
例如,输入c("a/b/c" = TRUE)
的结果应为:
E.g., input c("a/b/c" = TRUE)
should result in:
#> $a
#> $a$b
#> $a$b$c
#> [1] TRUE
我有一个解决方案,但是感觉很累:
I have a solution, but it feels pretty involved:
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).
免责声明
我确实四处张望(例如问题1 , 问题2 ),但我不太清楚找到我想要的东西.
Disclaimer
I did look around a bit (e.g. question 1, question 2), but I didn't quite find what I was looking for.
推荐答案
我写了一个执行类似功能的递归函数
I wrote a recursive function which does something similar
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
创建单独的字符向量
Basically recur.list
is a recursive function which creates a named nested list based on the number of "/" whereas listed_list.dirs
splits the name on "/" and creates a separate vector of characters for each of the 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
这篇关于基于命名矢量或列表的平面/压缩名称结构的嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!