【问题标题】:merging in R keeping all rows of a data set在 R 中合并,保留数据集的所有行
【发布时间】:2014-03-31 06:20:01
【问题描述】:

我有两个数据框

distinct_paper_year_data:

author_id      distinct_paper_year_count
     1                         3
     2                         1
     4                         1
     5                         4 

作者数据:

author_id    paper_id  confirmed
   1         25733         1
   2         47276         1
   3         79468         1
   4         12856         0

现在我想合并,以便所需的输出如下所示:

author_id  paper_id     confirmed    distinct_paper_year_count
 1            25733          1               3
 2            47276          1               1 
 3            79468          1               0  
 4            12856          0               4

在此,我需要在表 author_data 中出现的 author_ids 出现在最终输出中。由于 distinct_paper_year_count 中没有 author_id==3 的数据,因此 distinct_paper_year_count 列的值在最终结果中应为零(对于 author_id==3)。

通过使用合并我得到了

   merge(distinct_paper_year_data,author_data,by="author_id") 

author_id    distinct_paper_year_count paper_id confirmed
     1                         3       25733         1
     2                         1       47276         1
     4                         1       12856         0

怎样才能达到想要的输出?

【问题讨论】:

    标签: r merge


    【解决方案1】:

    你需要一个外连接:

    merge(distinct_paper_year_data,author_data,by="author_id", all=T)
    

    注意:对于表不匹配的那些行,您将获得 NA,例如 {3,5} 中的 author_id。也就是说,如果需要,您可以简单地修改 NA。您还可以使用all.xall.y 进行左外连接或右外连接。

    最后查看data.table 以获得更快的连接(和更多功能)

    【讨论】:

    • 我只需要 author_data 的行
    • @user3171906 ...好的。然后使用all.y = T
    猜你喜欢
    • 2021-10-10
    • 2023-01-20
    • 2020-10-11
    • 2018-03-22
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    相关资源
    最近更新 更多