在R中合并保留数据集的所有行

时间:2014-03-31 06:20:01

标签: r merge

我有两个数据框

distinct_paper_year_data:

author_id      distinct_paper_year_count
     1                         3
     2                         1
     4                         1
     5                         4 

author_data:

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_id中的author_data位于最终输出中。由于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

如何获得所需的输出?

1 个答案:

答案 0 :(得分:9)

您需要外部联接:

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

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

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

相关问题