[英]R: Convert list with different number of rows to data.frame
I would like to change this list to a data.frame: 我想将此列表更改为data.frame:
[[1]]
AA AB
21 1
[[2]]
AA AB
19 4
[[3]]
AA AB
23 1
[[4]]
AA AB BB
15 3 6
I tried "as.data.frame(r)", but I got the following error: 我试过“as.data.frame(r)”,但是我收到了以下错误:
Error in data.frame(c(21L, 1L), c(19L, 4L), c(23L, 1L), c(15L, 3L, 6L), :
arguments imply differing number of rows: 2, 3
How can I get something like: 我怎样才能得到类似的东西:
AA AB BB
V1 21 1
V2 19 4
V3 23 1
V4 15 3 6
If the list elements are named vectors, 如果列表元素是命名向量,
library(stringi)
res <- as.data.frame(t(stri_list2matrix(r)))
colnames(res) <- unique(unlist(sapply(r, names)))
res
# AA AB BB
#1 21 1 <NA>
#2 19 4 <NA>
#3 23 1 <NA>
#4 15 3 6
Or if the list elements are 'data.frame' 或者如果列表元素是'data.frame'
library(data.table)
rbindlist(r1, fill=TRUE)
r <- list(structure(c(21, 1), .Names = c("AA", "AB")), structure(c(19,
4), .Names = c("AA", "AB")), structure(c(23, 1), .Names = c("AA",
"AB")), structure(c(15, 3, 6), .Names = c("AA", "AB", "BB")))
r1 <- lapply(r, as.data.frame.list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.