我有一个 data.frames
的 list
(参见下面的 L
)。
我想知道是否可以将L
转换为我的如下所示的所需输出,即单个data.frame
?
L <- list(A = list(Short = data.frame(d = 1:2, SD = 3:4)),
B = list(Short = data.frame(d = 2:3, SD = 1:2), Long1 = data.frame(d = 7:8, SD = 6:7)),
C = list(Short = data.frame(d = 5:6, SD = 3:4), Long1 = data.frame(d = 8:9, SD = 1:2),
Long2 = data.frame(d = 4:5, SD = 6:7)))
所需输出(data.frame
):
d SD id
1 3 1
2 4 1
2 1 2
3 2 2
7 6 2
8 7 2
5 3 3
6 4 3
8 1 3
9 2 3
4 6 3
5 7 3
最佳答案
我们可以尝试重新绑定(bind)L
中的每个列表,并添加一个新列来表示列表编号,最后使用do.call
将整个列表放入一个数据帧中,并且rbind
。
output <- do.call(rbind, lapply(seq_along(L), function(x)
transform(do.call(rbind, L[[x]]), id = x)))
rownames(output) <- NULL
output
# d SD id
#1 1 3 1
#2 2 4 1
#3 2 1 2
#4 3 2 2
#5 7 6 2
#6 8 7 2
#7 5 3 3
#8 6 4 3
#9 8 1 3
#10 9 2 3
#11 4 6 3
#12 5 7 3
<小时/>
使用dplyr
的bind_rows
和purrr::map
可能会更短,但这给出了id
变量作为列表的名称(A
、B
、C
)而不是序列,应该不难更改。
library(dplyr)
bind_rows(purrr::map(L, bind_rows), .id = "id") %>%
mutate(id = match(id, unique(id)))
关于r - 将 data.frames 列表的列表转换为 R 中的单个 data.frame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57454864/