一個Base R
解決方案:
df1 = data.frame(col = list1, list1)
df2 = data.frame(col = list2, list2)
df3 = data.frame(col = list3, list3)
Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
# col list1 list2 list3
# 1 a a a a
# 2 b b <NA> b
# 3 c c c c
# 4 d d d <NA>
# 5 e <NA> <NA> e
# 6 f <NA> <NA> f
結果:
> Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))[,-1]
list1 list2 list3
1 a a a
2 b <NA> b
3 c c c
4 d d <NA>
5 <NA> <NA> e
6 <NA> <NA> f
或dplyr
+ purrr
:
library(dplyr)
library(purrr)
list(list1, list2, list3) %>%
map(~ data.frame(col = ., ., stringsAsFactors = FALSE)) %>%
reduce(full_join, by = "col") %>%
select(-col) %>%
setNames(paste0("list", 1:3))
數據:
list1 <- c("a", "b", "c", "d")
list2 <- c("a", "c", "d")
list3 <- c("a", "b", "c", "e", "f")
只需添加'[-1]'在你的函數結束。 – Masoud
@Masoud謝謝,我想說清楚'Reduce'實際上在做什麼 – useR