这里是purrr(tidyverse 的一部分)和基本 R 解决方案,假设您只想用NA 填充每个列表中的剩余值。我将任何列表的最大长度设为len,然后对于每个列表执行rep(NA),以获得 that 列表的长度与 any 的最大长度之间的差异em>列表。
library(tidyverse)
location <- list("USA","Singapore","UK")
organization <- list("Microsoft","University of London","Boeing","Apple")
person <- list()
date <- list("1989","2001","2018")
Jobs <- list("CEO","Chairman","VP of sales","General Manager","Director")
all_lists <- list(location, organization, person, date, Jobs)
len <- max(lengths(all_lists))
使用purrr::map_dfc,您可以映射列表列表,根据需要添加NAs,转换为字符向量,然后在一次管道调用中获取所有这些向量cbinded 的数据框:
map_dfc(all_lists, function(l) {
c(l, rep(NA, len - length(l))) %>%
as.character()
})
#> # A tibble: 5 x 5
#> V1 V2 V3 V4 V5
#> <chr> <chr> <chr> <chr> <chr>
#> 1 USA Microsoft NA 1989 CEO
#> 2 Singapore University of London NA 2001 Chairman
#> 3 UK Boeing NA 2018 VP of sales
#> 4 NA Apple NA NA General Manager
#> 5 NA NA NA NA Director
在基础 R 中,您可以在列表列表中使用 lapply 相同的函数,然后使用 Reduce 到 cbind 生成的列表并将其转换为数据框。采取两步而不是 purrr 的一步:
cols <- lapply(all_lists, function(l) c(l, rep(NA, len - length(l))))
as.data.frame(Reduce(cbind, cols, init = NULL))
#> V1 V2 V3 V4 V5
#> 1 USA Microsoft NA 1989 CEO
#> 2 Singapore University of London NA 2001 Chairman
#> 3 UK Boeing NA 2018 VP of sales
#> 4 NA Apple NA NA General Manager
#> 5 NA NA NA NA Director
对于这两者,您现在可以随意设置名称。