left_join分组数据集dplyr

时间:2016-05-03 22:28:22

标签: r dplyr

所以我开始使用一个具有用户ID值的数据集。每个ID值可能在数据集中出现多次,即ID: 77, 77, 77, 86, 86, 86, 86, 45, 45, ...

我所做的是group_by(ID),因此表格中只有一个ID值(我还在过程中平均了另一个数值变量)。我最终得到的是这个带有ID和AvgValue的新数据集,以及原始数据集。现在我想加入这两个数据集,以便将我的AvgValue作为一列,并且每个用户在表中的任何位置只有一个ID。

实施例

Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   1440 obs. of  5 variables:
 $ Id                     : int  77 77 77 77 77 77 77 77 77 77 ...
 $ Group                  : Factor w/ 6 levels " ","A","AA","C",..: 4 4 4 4 4 4 4 4 4 4 ...
 $ Sex                    : Factor w/ 2 levels "F","M": 1 1 1 1 1 1 1 1 1 1 ...
 $ Age                    : Factor w/ 49 levels "11y 10m 22d",..: 43 43 43 43 43 43 43 43 43 43 ...
 $ Value                  : num  79.2 82.9 83 83.6 84.2 ...

现在我group_by(ID)

Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   51 obs. of  2 variables:
 $ Id: int  77 83 84 85 86 87 88 89 90 91 ...
 $ AvgValue     : num  90.1 95.4 94.9 96.4 77.4 ...

现在,当我left_join时,

Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   1440 obs. of  6 variables:
     $ Id                     : int  77 77 77 77 77 77 77 77 77 77 ...
     $ AvgValue               : num  90.1 90.1 90.1 90.1 90.1 ...
     $ Group                  : Factor w/ 6 levels " ","A","AA","C",..: 4 4 4 4 4 4 4 4 4 4 ...
     $ Sex                    : Factor w/ 2 levels "F","M": 1 1 1 1 1 1 1 1 1 1 ...
     $ Age                    : Factor w/ 49 levels "11y 10m 22d",..: 43 43 43 43 43 43 43 43 43 43 ...
     $ Value                  : num  79.2 82.9 83 83.6 84.2 ...

而不是每个ID值只有一行。这可能吗?

1 个答案:

答案 0 :(得分:1)

你可以在加入后做一个截然不同的事。

res <- left_join(df1, df2, by = "Id") %>% distinct(Id)
相关问题