合并两个具有公共行和列的数据框(填写)

Combine two dataframes that have common rows and columns (fill in)

我有一个大数据框,我想用 SQL 查询许多数据库的结果来填充,可以这么说 "filling in data cubbyholes" 。皱纹:我不知道有多少小方块会被填满(有 group_by 年,所以我可能会得到一个包含一年或很多年的数据框)。

我很难弄清楚如何完成此操作。我正在尝试使用 dplyr 包..

如何获取新数据来填充小房间本身? (顺便说一句,我没有和 dplyr 结婚......我只是不想遍历新数据框的每个元素)

代码如下:

library(dplyr)
TargetDF <- structure(list(Ind = c(5, 6, 7), `2015 Act` = c(7870L, NA, NA
                                                            )), .Names = c("Ind", "2015 Act"), class = c("tbl_df", "data.frame"
                                                                                                         ), row.names = c(NA, -3L))

tempDF <- structure(list(Ind = 6, `2015 Act` = 49782L, `2016 Act` = 323L), .Names = c("Ind", 
                                                                                      "2015 Act", "2016 Act"), class = c("tbl_df", "tbl", "data.frame"
                                                                                      ), row.names = c(NA, -1L))
left_join(TargetDF,tempDF, by= "Ind")
## gives duplicate columns

left_join(TargetDF,tempDF)
## loses the new "2015 Act" data for Ind 6

bind_cols(TargetDF,tempDF)
## don't work

bind_rows(TargetDF,tempDF)
## double Ind 6 (there are other columns nor included here, which is why I can't !is.na() to eliminate duplicate Ind 6)

一种可能的方法是从按 Ind 分组的每一列中获取非 NA 值,否则,留下(生成)一个 NA

full_join(TargetDF, tempDF) %>% 
  group_by(Ind) %>% 
  summarise_each(funs(.[!is.na(.)][1L]))

# Source: local data frame [3 x 3]
# 
#     Ind 2015 Act 2016 Act
#   (dbl)    (int)    (int)
# 1     5     7870       NA
# 2     6    49782      323
# 3     7       NA       NA

我们可以使用 {powerjoin},进行左连接并使用 coalesce_xy(实际上是 dplyr::coalesce)处理冲突:

library(powerjoin)
safe_left_join(TargetDF, tempDF, by = "Ind", conflict = coalesce_xy)
# # tibble [3 x 3]
#     Ind `2015 Act` `2016 Act`
#   <dbl>      <int>      <int>
# 1     5       7870         NA
# 2     6      49782        323
# 3     7         NA         NA