r中嵌套列表的第二个[给定]级别的提取名称
我有一个嵌套列表。该列表的每个级别均为命名(如提供的虚拟示例中)。我想从初始列表的第二级中提取名称(唯一),因此我将能够在进一步的操作中使用它们。
我知道如何分两个步骤进行操作,但是我想知道是否有更高效/优雅的解决方案。我也想知道,正则方法是否会更快(我在正则是菜鸟)。
这是一个虚拟列表:
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))
I have a nested list. Each level of this list is named (as in provided dummy example). I want to extract the names (unique) from the 2nd level of my initial list, so I will be able to use them in some further operations.
I know how to do it in two steps, but I wonder whether there is more efficient/elegant solution. Also I wonder whether the regex approach would be faster (I am noob at regex).
Here is a dummy list:
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)))
And here is my code:
allnames <- names(rapply(x, function(x) head(x, 1)))
desirednames <- unique(sapply(strsplit(allnames, ".", fixed=TRUE), "[", 2))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
基本
r的第二级解决方案:R:Solution for second level in
base
R:基于
purrr :: map_depth
的可能解决方案:A possible solution, based on
purrr::map_depth
:这样做的一种简洁的方法:
如果列表元素只有
“ names”
属性,则简化为:如果名称烦恼您,请将其输入
unname
。A concise way of doing this:
If the list elements just have the
"names"
attribute, this simplifies to:If the names annoy you, pipe it into
unname
.