提取 R 中嵌套列表的第二[给定]级别的名称

问题描述 投票:0回答:3

我有一个嵌套列表。该列表的每个级别均已命名(如提供的虚拟示例中所示)。我想从初始列表的第二级中提取名称(唯一),这样我就可以在一些进一步的操作中使用它们。

我知道如何分两步完成,但我想知道是否有更高效/优雅的解决方案。我也想知道正则表达式方法是否会更快(我是正则表达式菜鸟)。

这是一个虚拟列表:

x <- list(one = list(one_1 = list(seq = 1:9, start = 1, end = 5),
                     one_2 = list(seq = 2:11, start = 2, end = 6),
                     one_3 = list(seq = 3:12, start = 3, end = 7)),
          two = list(two_1 = list(seq = 1:13, start = 8, end = 222),
                     two_2 = list(seq = 1:14, start = 13, end = 54)))

这是我的代码:

allnames <- names(rapply(x, function(x) head(x, 1)))
desirednames <- unique(sapply(strsplit(allnames, ".", fixed=TRUE), "[", 2))
r nested-lists names
3个回答
9
投票

base
R 中第二级的解决方案:

unlist(lapply(names(x), function(n) names(x[[n]])))
[1] "one_1" "one_2" "one_3" "two_1" "two_2"

8
投票

一个可能的解决方案,基于

purrr::map_depth

library(tidyverse)

map_depth(x, 1, names) %>% unlist(use.names = F)

#> [1] "one_1" "one_2" "one_3" "two_1" "two_2"

3
投票

执行此操作的简洁方法:

unlist(lapply(x, \(x) attributes(x)[['names']])) 
#    one1    one2    one3    two1    two2 
# "one_1" "one_2" "one_3" "two_1" "two_2"

如果列表元素只有

"names"
属性,则可以简化为:

unlist(lapply(x, attributes))
# one.names1 one.names2 one.names3 two.names1 two.names2 
#    "one_1"    "one_2"    "one_3"    "two_1"    "two_2" 

如果这些名字让您烦恼,请将其通过管道输入

unname

unlist(lapply(x, attributes)) |> unname()
# [1] "one_1" "one_2" "one_3" "two_1" "two_2"
© www.soinside.com 2019 - 2024. All rights reserved.