我有一个嵌套列表。此列表的每个级别都是命名的(如所提供的虚拟示例所示)。我想从我的初始列表的第二层提取名字(唯一的),所以我将能够在一些进一步的操作中使用它们。
我知道如何分两步完成,但我不知道是否有更高效/优雅的解决方案。另外,我想知道regex方法是否会更快(我是regex的新手)。
下面是一个虚拟列表:
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))发布于 2022-07-06 11:30:00
一种基于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"发布于 2022-07-06 11:35:44
base R中的第二级解决方案:
unlist(lapply(names(x), function(n) names(x[[n]])))
[1] "one_1" "one_2" "one_3" "two_1" "two_2"发布于 2022-07-06 14:53:06
这样做的简明方法:
unlist(lapply(x, \(x) attributes(x)[['names']]))
# one1 one2 one3 two1 two2
# "one_1" "one_2" "one_3" "two_1" "two_2"如果list元素只具有"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"https://stackoverflow.com/questions/72882780
复制相似问题