[英]Converting list of lists to a data frame in R
我正在使用 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
我知道錯誤意味着什么,但不知道如何修復它。 想法?
我們可以通過melt/dcast
來做到這melt/dcast
。 我們設置list
元素的名稱, melt
將list
轉換為data.frame
。 我們創建一個序列列('ind'),在將'data.frame' 轉換為'data.table' 后,按L 列(即L1、L2、L3)分組。 然后我們使用dcast
的 devel 版本中的data.table
將“long”重塑為“wide”。
library(reshape2)
library(data.table)#v1.9.5+
d1 <- melt(setNames(L, seq_along(L)))
setDT(d1)[, ind:= c('start', 'end')[1:.N], .(L1, L2, L3)]
res <- setnames(dcast(d1, L1+L2~ind, value.var='value'),
1:2, c('config', 'alpha'))
res[,c(1:2, 4:3)]
# config alpha start end
#1: 1 1 0 0
#2: 1 2 0 0
#3: 1 3 33 37
#4: 2 1 0 0
#5: 2 2 0 0
#6: 2 3 29 33
對於第二個list
('L1'),我們執行相同的過程。 我們可以像前一種情況一樣更改列名。
d2 <- melt(setNames(L1, seq_along(L1)))
setDT(d2)[, ind:= 1:.N, .(L1, L2)]
dcast(d2, L1+L2~ind, value.var='value')
雖然這不是一個完整的答案,但它可能會讓您走上正確的道路。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.