【问题标题】:Aggregate rows by group_by conditional按 group_by 条件聚合行
【发布时间】:2018-03-29 15:20:51
【问题描述】:

如果可能,我想在 dplyr 中解决这个问题。

我有一个数据框:

Item         Count
Bike Tire    15
Car Tire     6
H. Window    3
S. Windows   7
Spare Tires  1
Widget X     88
Widget Z     34
...

我想让数据框聚合到:

Item       Count
Tires      22
H. Window  3
S. Windows 7 
Widget X   88
Widget Z   34
...

我已经到了filter(data, grepl(glob2rx("*tire*"), data$Item, ignore.case = TRUE) 这样我就可以看到哪些行会匹配,但是我如何group_by 才能聚合示例中的数据?我可能也会对其他项目做同样的事情,但只是想先了解基本情况。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    这是replace 'Item' 的一个选项,在group_by 中具有'tire' 子字符串和'Tires' 并获得'Count' 的sum

    library(dplyr)
    df1 %>%
       group_by(Item = replace(Item, grepl("Tire", Item), "Tires")) %>%
       summarise(Count = sum(Count))
    # A tibble: 5 x 2
    #  Item       Count
    #  <chr>      <int>
    #1 H. Window      3
    #2 S. Windows     7
    #3 Tires         22
    #4 Widget X      88
    #5 Widget Z      34
    

    【讨论】:

    • 你是说轮胎吗?
    • @Shawn 对不起,是轮胎。更新
    • 所以最终替换首先发生,此时 group_by 实际上只是一个明确的 group by=Item。您也可以在 group by 之外完成替换,并且只保留 group_by(Item)。这很有趣。
    • @Shawn 是的,你可以在mutate 中进行,然后在group_by 中进行,但我想我会省去一步
    猜你喜欢
    • 2020-01-07
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 2022-12-06
    • 1970-01-01
    相关资源
    最近更新 更多