gpt4 book ai didi

递归地将函数应用于列表元素

转载 作者:行者123 更新时间:2023-12-04 09:40:14 25 4
gpt4 key购买 nike

使用 rmatio包,我得到类似于以下的嵌套列表:

nestedlist <- list(
a = list( a = list(1:10), b = list(35)),
b = list(11:25)
)

理想情况下,我希望它看起来像这样(所有列表都有一个未命名的元素被元素替换):
nestedlist <- list(a = list(a=1:10, b=35), b = 11:25)

我尝试了已经尝试过的以下内容:
unlist(nestedlist) # returns one vector with all elements

selective_unlist <- function(e)
if(is.list(e) &&is.null(names(e))) unlist(e) else e

# only calls the function with each leaf, so nothing gets replaced
rapply(nestedlist, how='replace', selective_unlist)

# works, but only for 2 levels
lapply(nestedlist, selective_unlist)

# works, but using explicit recursion is slow for large datasets
recursive_selective_unlist <- function(e)
if(is.list(e)) {
if(is.null(names(e))) unlist(e)
else lapply(e, recursive_selective_unlist)
} else e

有没有更好/更快的方法来简化这些嵌套列表,还是递归函数是我最好的选择?

最佳答案

按照@Pafnucy 的想法,我会使用

ff <- function(x) if (is.list(x[[1]])) lapply(x,ff) else unlist(x)

哪个
ff(nestedlist)
# $a
# $a$a
# [1] 1 2 3 4 5 6 7 8 9 10
#
# $a$b
# [1] 35
#
#
# $b
# [1] 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# check result:
identical(list(a = list(a=1:10, b=35), b = 11:25),ff(nestedlist))
# [1] TRUE

关于递归地将函数应用于列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30487010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com