【问题标题】:R add rows to grouped df using dplyrR使用dplyr将行添加到分组的df
【发布时间】:2019-04-29 03:07:12
【问题描述】:

我有一个分组的 df,我想在与 df 中的变量 (item_code) 匹配的组顶部添加额外的行。 其他行没有id 列。额外的行不应在df 的组内重复。

示例数据:

df <- as.tibble(data.frame(id=rep(1:3,each=2),
                     item_code=c("A","A","B","B","B","Z"),
                     score=rep(1,6)))



additional_rows <- as.tibble(data.frame(item_code=c("A","Z"),
                                        score=c(6,6)))

我尝试了什么

我找到了这篇文章并尝试应用它: Add row in each group using dplyr and add_row()

df %>% group_by(id) %>% do(add_row(additional_rows %>%
                                     filter(item_code %in% .$item_code)))

我得到了什么:

# A tibble: 9 x 3
# Groups:   id [3]
     id item_code score
  <int> <fct>     <dbl>
1     1 A             6
2     1 Z             6
3     1 NA           NA
4     2 A             6
5     2 Z             6
6     2 NA           NA
7     3 A             6
8     3 Z             6
9     3 NA           NA

我在寻找什么:

# A tibble: 6 x 3
     id item_code score
  <int> <fct>     <dbl>
1     1 A             6
2     1 A             1
3     1 A             1
4     2 B             1
5     2 B             1
6     3 B             1
7     3 Z             6
8     3 Z             1 

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    这应该可以解决问题:

     library(plyr)
    
     df %>%
       join(subset(df, item_code %in% additional_rows$item_code, select = c(id, item_code)) %>%
            join(additional_rows) %>% 
            subset(!duplicated(.)), type = "full") %>%
       arrange(id, item_code, -score)
    

    不确定它是否是最好的方法,但它有效

    编辑:为了以相同的顺序获得分数,添加了其他排列项

    编辑 2:好的,现在应该不会根据您的评论从其他行添加重复的行

    【讨论】:

    • 它适用于样本数据 true。然而,真正的数据additional_rows 不仅仅是item_code Adf 匹配。
    • 能否添加完整的数据,以便我查看是否可以修改?
    • 您是否总是想从输出中排除 Z?这有点限制,我不确定这样做的目的是什么
    • 已编辑以确保保留所有匹配的内容。这适用于完整数据吗?
    • 好的,我又做了一个调整。你能检查它现在是否有效吗?
    猜你喜欢
    • 1970-01-01
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 2016-02-07
    相关资源
    最近更新 更多