我有一个嵌套的列表.嵌套列表的"中心"是一个包含n个整数的向量.我需要计算每个嵌套列表中有多少个整数,然后取消上面的一个级别,以获得这些计数的向量(即,不是嵌套中心的list(0, 1:5, 0, 0, 1:3)
,而是c(0, 5, 0, 0, 3)
).
这似乎相对简单——我能够用rapply
完成第一部分,即将list(0, 1:5, 0, 0, 1:3)
转换为list(0, 5, 0, 0, 3)
.My specific question我需要的帮助是如何将最里面的列表取消到向量(而不是list(0, 5, 0, 0, 3)
我想要c(0, 5, 0, 0, 3)
)
我已经搜索并try 了各种各样的apply
、lapply
、unlist
方法,但没有一种是完全正确的,因为它们的目标是最里面的列表.因为我想取消列出的列表是倒数第二个元素,所以我正在努力找到一种优雅地完成这一点的方法.
在下面的示例数据中,我可以通过两种方式获得所需的结果:多个lapply
函数或一个for
循环.然而,我的实际数据包含更多的列表和数百万个数据点,因此这些可能不是有效的选项.
下面是(1)样本数据,(2)我try 过的,以及(3)具有所需 struct 的样本数据.
样本数据
have_list <- list(scenario1 = list(method1 = list(place1 = list(0, 1:5, 0, 0, 1:3),
place2 = list(1:2, 0, 1:10, 0, 0),
place3 = list(0:19, 0, 0, 0, 0),
place4 = list(1:100, 0, 0, 1:4, 0)),
method2 = list(place1 = list(1:5, 1:5, 0, 0, 1:3),
place2 = list(0, 0, 1:5, 0, 0),
place3 = list(0:19, 0, 1:7, 0, 0),
place4 = list(1:22, 0, 0, 1:4, 0)),
method3 = list(place1 = list(0, 1:2, 1:6, 0, 1:3),
place2 = list(1:2, 0, 1:6, 1:4, 0),
place3 = list(0:19, 0, 0, 0, 1:2),
place4 = list(1:12, 0, 0, 1:12, 0))),
scenario2 = list(method1 = list(place1 = list(0, 1:5, 0, 0, 1:3),
place2 = list(1:2, 0, 1:10, 0, 0),
place3 = list(0:19, 0, 0, 0, 0),
place4 = list(1:100, 0, 0, 1:4, 0)),
method2 = list(place1 = list(1:5, 1:5, 0, 0, 1:3),
place2 = list(0, 0, 1:5, 0, 0),
place3 = list(0:19, 0, 1:7, 0, 0),
place4 = list(1:22, 0, 0, 1:4, 0)),
method3 = list(place1 = list(0, 1:2, 1:6, 0, 1:3),
place2 = list(1:2, 0, 1:6, 1:4, 0),
place3 = list(0:19, 0, 0, 0, 1:2),
place4 = list(1:12, 0, 0, 1:12, 0))))
我试过的
因此,我访问了一些问题:
# Get number of integers in each nested list
lengths <- rapply(have_list, function(x) unlist(length(x)), how = "list") # this works fine
#' Each count is currently still in its own list of length 1,
#' Convert each count to vector
#' In the "middle" the nested list:
# I have list(0, 5, 0, 0, 3)
# I want c(0, 5, 0, 0, 3)
# Attempts to unlist the counts
# Unlist the counts
test1 <- rapply(lengths, unlist, how = "list") # doesn't work
test2 <- unlist(lengths, recursive = FALSE) # doesn't work
test3 <- lapply(lengths, function(x) lapply(x, unlist)) # doesnt work
test4 <- lapply(lengths, function(x) lapply(x, unlist, recursive = FALSE)) # doesnt work
test5 <- rapply(have_list, function(x) unlist(length(x)), how = "list") #doesnt work
test6 <- rapply(have_list, function(x) unlist(length(x)), how = "unlist") #doesnt work
我想要的数据 struct
# This works on test data but is impractical for real data
want_list <- lapply(lengths, function(w) lapply(w, function(x) lapply(x, unlist)))
# or
want_list <- lengths
## for loops work but is not practical
for (i in 1:length(lengths)){
for (j in 1:length(lengths[[i]])){
for (k in 1:length(lengths[[i]][[j]])){
want_list[[i]][[j]][[k]] <- unlist(lengths[[i]][[j]][[k]])
}
}
}