rbind 数据框列表,一列中只有一些公共元素

rbind list of dataframes with only some common elements in one column

我有一个数据帧列表list1

 df1 <- data.frame(ID = paste0(LETTERS[1],1:4), valueA = seq(0.1,0.4,0.1), Category= "Apples")
df2 <- data.frame(ID = paste0(LETTERS[1],3:6), valueB = seq(0.1,0.4,0.1),  Category= "Apples")
df3 <- data.frame(ID = paste0(LETTERS[1],4:7), valueC = seq(0.1,0.4,0.1),  Category= "Apples")

list1 <- list(df1,df2,df3)

list1
   [[1]]
  ID valueA Category
1 A1    0.1   Apples
2 A2    0.2   Apples
3 A3    0.3   Apples
4 A4    0.4   Apples

[[2]]
  ID valueB Category
1 A3    0.1   Apples
2 A4    0.2   Apples
3 A5    0.3   Apples
4 A6    0.4   Apples

[[3]]
  ID valueC Category
1 A4    0.1   Apples
2 A5    0.2   Apples
3 A6    0.3   Apples
4 A7    0.4   Apples

我想 rbind 它在一起,但匹配每个数据帧中的公共 ID 字段,以便它们出现在同一行中

想要的结果:

   ID valueA Category valueB valueC
1  A1    0.1   Apples     NA     NA
2  A2    0.2   Apples     NA     NA
3  A3    0.3   Apples    0.1     NA
4  A4    0.4   Apples    0.2    0.1
7  A5     NA   Apples    0.3    0.2
8  A6     NA   Apples    0.4    0.4
12 A7     NA   Apples     NA    0.4

我尝试使用 rbind.fill(list1),但每个数据框组合成单独的行。也很高兴将其转换为所需的结果:

 ID valueA Category valueB valueC
1  A1    0.1   Apples     NA     NA
2  A2    0.2   Apples     NA     NA
3  A3    0.3   Apples     NA     NA
4  A4    0.4   Apples     NA     NA
5  A3     NA   Apples    0.1     NA
6  A4     NA   Apples    0.2     NA
7  A5     NA   Apples    0.3     NA
8  A6     NA   Apples    0.4     NA
9  A4     NA   Apples     NA    0.1
10 A5     NA   Apples     NA    0.2
11 A6     NA   Apples     NA    0.3
12 A7     NA   Apples     NA    0.4

这应该有效:

Reduce(function(x, y) merge(x, y, all=TRUE), list1)

你不能使用 merge() 语句吗?

dd<-merge(df1,df2,by=intersect(names(df1),names(df2)),all=T)
dd<-merge(dd,df3,by=intersect(names(dd),names(df3)),all=T)
library(purrr)
library(dplyr)

df1 <- data_frame(ID = paste0(LETTERS[1],1:4), valueA = seq(0.1,0.4,0.1), Category= "Apples")
df2 <- data_frame(ID = paste0(LETTERS[1],3:6), valueB = seq(0.1,0.4,0.1),  Category= "Apples")
df3 <- data_frame(ID = paste0(LETTERS[1],4:7), valueC = seq(0.1,0.4,0.1),  Category= "Apples")

list1 <- list(df1, df2, df3)

reduce(list1, full_join)
## # A tibble: 7 × 5
##      ID valueA Category valueB valueC
##   <chr>  <dbl>    <chr>  <dbl>  <dbl>
## 1    A1    0.1   Apples     NA     NA
## 2    A2    0.2   Apples     NA     NA
## 3    A3    0.3   Apples    0.1     NA
## 4    A4    0.4   Apples    0.2    0.1
## 5    A5     NA   Apples    0.3    0.2
## 6    A6     NA   Apples    0.4    0.3
## 7    A7     NA   Apples     NA    0.4