【问题标题】:R: Convert list with different number of rows to data.frameR:将具有不同行数的列表转换为data.frame
【发布时间】:2015-03-22 20:52:49
【问题描述】:

我想将此列表更改为 data.frame:

[[1]]


AA AB 
21  1 

[[2]]

AA AB 
19  4 

[[3]]

AA AB 
23  1 

[[4]]

AA AB BB 
15  3  6 

我尝试了“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

我怎样才能得到类似的东西:

   AA AB BB
V1 21  1
V2 19  4
V3 23  1
V4 15  3 6

【问题讨论】:

  • 列表中有 data.frame 对象还是只是命名为向量? dput 输出会非常有用

标签: r list dataframe


【解决方案1】:

如果列表元素被命名为向量,

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

或者如果列表元素是'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)

【讨论】:

  • @akrun。你对library(stringi) 的建议很棒。我有list elements are named vectors,但问题出在colnames(res) 上,我得到的不是原来的colnames,而是数字。
  • @Googme 感谢您的反馈。你能把它作为一个单独的问题发布吗?
猜你喜欢
  • 2013-04-07
  • 2020-11-22
  • 1970-01-01
  • 2019-07-24
  • 2020-07-17
  • 2018-10-26
  • 2022-01-02
  • 1970-01-01
  • 2014-05-17
相关资源
最近更新 更多