【问题标题】:Combine two dataframes that have common rows and columns (fill in)合并两个具有共同行和列的数据框(填写)
【发布时间】:2016-02-08 11:05:36
【问题描述】:

我有一个大数据框,我想用从 SQL 查询到许多数据库的结果来填充它,可以说是“填充数据小洞”。 Wrinkle:我不知道会填充多少个cubbyholes(有一个group_by year,所以我可能会得到一个包含一年或很多个的数据框)。

我很难弄清楚如何做到这一点。我正在尝试使用 dplyr 包..

  • left_join 要么将同一行添加两次(如果我指定 by=),要么删除新列(如果我没有指定 by= 并因此它加入两个相似的列)

  • bind_cols 不起作用

  • bind_rows 添加重复行。

如何获取新数据来填充小房间本身? (顺便说一句,我没有与 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)

【问题讨论】:

  • Myabe 类似full_join(TargetDF, tempDF) %&gt;% group_by(Ind) %&gt;% summarise_each(funs(sum(., na.rm = TRUE)))
  • 谢谢,解决了这个例子,但是我在这里压制的一些列是字符,因此 summarise_each 的结果是Error: invalid 'type' (character) of argument
  • 也许full_join(TargetDF, tempDF) %&gt;% group_by(Ind) %&gt;% summarise_each(funs(.[!is.na(.)][1]))
  • 是的,做到了!太棒了......所以你传递的函数只是'所有东西的第一个非NA值'??哇,伙计,你是个艺术家。为代表写正式答案?
  • 其实[1]部分是针对所有值都是NAs的情况。这样,我们生成了一个NA,因为NA[1] 也是NA。否则summarise_each 将返回错误。我会发布一个答案,但我觉得可能会有更多的 dplyrish 方式。

标签: r join data-binding bind dplyr


【解决方案1】:

一种可能的方法是从按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

【讨论】:

    【解决方案2】:

    我们可以使用{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
    

    【讨论】:

      猜你喜欢
      • 2020-12-04
      • 1970-01-01
      • 2015-03-21
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 2020-10-27
      • 1970-01-01
      • 2021-12-17
      相关资源
      最近更新 更多