在R中将列表对象转换为数据框

12

我有一个如下所示的列表嵌套列表。我想将其转换为所需格式的数据框。

myList:

[[1]]
NULL

[[2]]
[[2]]$`file`
[1] "ABC"

[[2]]$New
[1] 21

[[2]]$Old
[1] 42


[[3]]
[[3]]$`file`
[1] "CDF"

[[3]]$NEW
[1] 206

[[3]]$Old
[1] 84

我想将这个嵌套列表对象转换为所需格式的数据框:

file   New   Old
ABC    21     42
CDF    206    84

提前感谢!


@RichScriven,谢谢,它起作用了,下次我会提供可重现的示例。 - user15051990
可能是R - list to data frame的重复问题。 - A. Suliman
不太对。这是一个嵌套列表。 - Rich Scriven
@RichScriven请查看Ian Sudbery的答案。 - A. Suliman
当然可以。如果你喜欢冗长、复杂的代码。 - Rich Scriven
将嵌套列表转换为数据框。 - Henrik
3个回答

21
我们可以在转换为之后使用map_df
library(tidyverse)
myList %>% 
   map_df(as_tibble)
# A tibble: 2 x 3
#  file    New   Old
#  <chr> <dbl> <dbl>
#1 ABC      21    42
#2 CDF     206    84

使用bind_rows函数进行合并

bind_rows(myList)
# A tibble: 2 x 3
#  file    New   Old
#  <chr> <dbl> <dbl>
#1 ABC      21    42
#2 CDF     206    84

数据

myList <- list(NULL, list(file = 'ABC', New = 21, Old = 42), 
                      list(file = 'CDF', New = 206, Old = 84))

9

类似这样(ls是你的列表):

df <- data.frame(matrix(unlist(ls), ncol = max(lengths(ls)), byrow = TRUE))

如果列名很重要,那么:
names(df) <- names(ls[[which(lengths(ls)>0)[1]]])

1
Warning message: In matrix(unlist(myLIST), ncol = max(lengths(myLIST)), byrow = TRUE) : data length [20000] is not a sub-multiple or multiple of the number of rows [1000] - PM0087

8
似乎以下方法可以解决问题。
do.call(rbind, lapply(list, as.data.frame))

其中list是您的列表。


Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : arguments imply differing number of rows: 1, 0 - PM0087

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接