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

时间:2017-01-12 16:00:41

标签: r list dplyr rbind

我有一个数据框列表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

3 个答案:

答案 0 :(得分:4)

这应该有效:

func scrollViewDidScroll(_ scrollView: UIScrollView)

答案 1 :(得分:2)

你不能使用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)

答案 2 :(得分:2)

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