我正在 R 中使用嵌套列表,并且遇到了 rbindlist 的问题。我的列表看起来像这样
L <- list(list(list(c(0,0)),list(c(0,0)),list(c(33,37))), list(list(c(0,0)),list(c(0,0)),list(c(29,33))))
结果:
[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
[1] 0 0
[[1]][[2]]
[[1]][[2]][[1]]
[1] 0 0
[[1]][[3]]
[[1]][[3]][[1]]
[1] 33 37
[[2]]
[[2]][[1]]
[[2]][[1]][[1]]
[1] 0 0
[[2]][[2]]
[[2]][[2]][[1]]
[1] 0 0
[[2]][[3]]
[[2]][[3]][[1]]
[1] 29 33
我想做的是将每个子列表折叠成一个看起来像这样的数据框(这个结果是我想要从上面的第一组列表中得到的结果):
config alpha start end
1 1 0 0
1 2 0 0
1 3 33 37
2 1 0 0
2 2 0 0
2 3 29 33
但某些列表相对于子列表中的其他列表具有不同数量的子列表。例如,这样的列表(中间有 2 个子列表,而不是 3 个 1-sublist 子列表)。
L <- list(list(c(0,0)), list(c(1,4),c(5,9)), list(c(0,0)) )
[[1]]
[[1]][[1]]
[1] 0 0
[[2]]
[[2]][[1]]
[1] 1 4
[[2]][[2]]
[1] 5 9
[[3]]
[[3]][[1]]
[1] 0 0
当我尝试 rbindlist 时,出现此错误:
> rbindlist(lapply(master_init, as.list))
Error in rbindlist(lapply(master_init, as.list)) :
Column 2 of item 50 is length 2, inconsistent with first column of that item which is length 1. rbind/rbindlist doesn't recycle as it already expects each item to be a uniform list, data.frame or data.table
我知道错误的含义,但不知道如何修复它。想法?
最佳答案
虽然这不是一个完整的答案,但它可能会让您走上正确的道路。
L1 <- list(list(list(c(0,0)),list(c(0,0)),list(c(33,37))), list(list(c(0,0)),list(c(0,0)),list(c(29,33))))
L2 <- list(list(c(0,0)), list(c(1,4),c(5,9)), list(c(0,0)))
as.data.frame(matrix(unlist(L1), ncol = 2, byrow = TRUE))
V1 V2
1 0 0
2 0 0
3 33 37
4 0 0
5 0 0
6 29 33
as.data.frame(matrix(unlist(L2), ncol = 2, byrow = TRUE))
V1 V2
1 0 0
2 1 4
3 5 9
4 0 0
关于r - 将列表列表转换为 R 中的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32262784/