[英]How to unnest lists in a list into a list?
Consider the minimal working example考虑最小的工作示例
raw_list <- list(1, 2)
process_list <- function(item) {
if(item == 1) {
return(list(c(1, 1), c(2, 2)))
}
else {
return(c(3, 3))
}
}
processed_list <- lapply(raw_list, process_list)
df <- do.call(rbind, processed_list)
processed_list
is processed_list
是
[[1]]
[[1]][[1]]
[1] 1 1
[[1]][[2]]
[1] 2 2
[[2]]
[1] 3 3
and df
is和df
是
[,1] [,2]
[1,] numeric,2 numeric,2
[2,] 3 3
How do I unnest processed_list
to get如何取消嵌套processed_list
列表以获取
[[1]]
[1] 1 1
[[2]]
[1] 2 2
[[3]]
[1] 3 3
or how do I unnest df
to get或者我如何取消嵌套df
以获得
[,1] [,2]
[1,] 1 1
[2,] 2 2
[3,] 3 3
I think you should also list
the c(3, 3)
in the function, then unlist
non-recursively.我认为您还应该在函数中list
c(3, 3)
,然后unlist
非递归方式取消列出。
raw_list <- list(1, 2)
process_list <- function(item) {
if(item == 1) {
return(list(c(1, 1), c(2, 2)))
}
else {
return(list(c(3, 3)))
}
}
processed_list <- lapply(raw_list, process_list)
unlist(processed_list, recursive=FALSE)
# [[1]]
# [1] 1 1
#
# [[2]]
# [1] 2 2
#
# [[3]]
# [1] 3 3
you could simply use你可以简单地使用
simple_list <- unlist(processed_list, recursive = FALSE)
and then simply然后简单地
df <- do.call(rbind, simple_list)
this gives:这给出了:
[[1]]
[1] 1 1
[[2]]
[1] 2 2
[[3]]
[1] 3
[[4]]
[1] 3
and和
[,1] [,2]
[1,] 1 1
[2,] 2 2
[3,] 3 3
[4,] 3 3
Try this尝试这个
processed_list[[2]] <- list(processed_list[[2]])
processed_list <- processed_list |> unlist(recursive = FALSE)
df <- do.call(rbind, processed_list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.