【问题标题】:left_join a grouped dataset dplyrleft_join 分组数据集 dplyr
【发布时间】:2016-05-03 22:28:21
【问题描述】:

所以我从一个包含用户 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 值只有一行。这可能吗?

【问题讨论】:

  • 只需group_by(Id, group, Sex, Age),不要使用left_join
  • @HubertL 但它不会折叠 ID。

标签: r dplyr


【解决方案1】:

你可以在加入后做一个 distinct。

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

【讨论】:

    猜你喜欢
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2018-05-21
    • 2021-03-24
    • 1970-01-01
    • 2022-01-14
    相关资源
    最近更新 更多