将具有不均匀矩阵的列表强制转换为 tibble

coerce list with uneven matrices into tibble

我有一个这样的列表:

lst <-
list(structure(c("1", "[19]"), .Dim = 1:2), structure("1", .Dim = c(1L, 
1L)), structure(c("1", "[41]"), .Dim = 1:2), structure(c("1", 
"[55]"), .Dim = 1:2), structure(c("1", "[56]"), .Dim = 1:2), 
    structure(c("1", "[84]"), .Dim = 1:2))

如何将其转换为 tibble 以便:

rslt <-
tibble(batch=c(1,1,1,1,1,1), id=c("[19]","","[41]","[55]","[56]","[84]"))

# A tibble: 6 x 2
  batch    id
  <dbl> <chr>
1     1  [19]
2     1      
3     1  [41]
4     1  [55]
5     1  [56]
6     1  [84]

我们遍历 lst 并将其转换为 data.frame,因为它是 matrix。通常,如果尺寸相同,使用 do.call(rbind, lst) 应该有效。但是,这里不一样。使用 purrr 中的 map_dfr,我们遍历每个 lst 元素,应用函数 as.data.frame 将其转换为 data.frame,同时,我们得到我们使用的单个数据集 map_dfr

map_dfr() and map_dfc() return data frames created by row-binding and column-binding respectively. They require dplyr to be installed.

library(purrr)
map_dfr(lst, ~as.data.frame(., stringsAsFactors=FALSE))

注意:它 returns 不存在元素,它比空白元素更好

plyr包中还有一个非常方便的函数可以轻松处理,

plyr::rbind.fill(lapply(lst, as.data.frame))

#  V1   V2
#1  1 [19]
#2  1 <NA>
#3  1 [41]
#4  1 [55]
#5  1 [56]
#6  1 [84]