【发布时间】:2021-04-03 00:54:44
【问题描述】:
我需要在 R 中聚合数据。我有 8 列,其中 3 列是分类的,其中 5 列是数字的,需要根据来自 2 个分类变量的条件组合有条件地求和。我的数据如下所示:
df <- structure(list(Color = c("Red", "Blue", "Blue", "Red", "Yellow"
), Weekend = c(1L, 0L, 1L, 0L, 1L), LeapYear = c(1L, 1L, 0L,
0L, 0L), Length = c(15L, 20L, 10L, 15L, 15L), Height = c(50L,
70L, 35L, 28L, 80L), Weight = c(120L, 130L, 120L, 105L, 140L),
Cost = c(25L, 50L, 55L, 65L, 80L), Purchases = c(5L, 10L,
5L, 10L, 15L)), class = "data.frame", row.names = c(NA, -5L
))
> df
Color Weekend LeapYear Length Height Weight Cost Purchases
1 Red 1 1 15 50 120 25 5
2 Blue 0 1 20 70 130 50 10
3 Blue 1 0 10 35 120 55 5
4 Red 0 0 15 28 105 65 10
5 Yellow 1 0 15 80 140 80 15
我想用条件求和聚合这个表,
例如,总长度和高度,但仅适用于闰年,总和高度和成本,但仅适用于闰年和周末。
我希望这些按颜色分组的条件总和如下所示:
| Color | Length | Height | Weight | Cost | Purchases | Length_LeapYear | Height_LeapYear | Height_LeapYear_Weekend | Cost_LeapYear_Weekend | Purchases_Weekend |
|---|---|---|---|---|---|---|---|---|---|---|
| Red | 30 | 78 | 225 | 90 | 15 | 15 | 50 | 50 | 25 | 5 |
| Blue | 30 | 105 | 250 | 105 | 15 | 20 | 70 | 0 | 0 | 5 |
| Yellow | 15 | 80 | 140 | 80 | 15 | 0 | 0 | 0 | 0 | 15 |
我在 dplyr 工作,并且使用 summarise_at() 在相同条件下对多个字段求和:
df %>%
group_by(Color, Weekend, LeapYear) %>%
summarise_at(c(Length_LeapYear == "Length", Height_LeapYear == "Height"), ~sum(.[LeapYear==1]))
但是当我尝试为剩余的条件求和变量添加条件时,这会删除我之前的总结。这是我想象代码如何工作的想法。
df %>%
group_by(Color, Weekend, LeapYear) %>%
summarise_at(c("Length", "Height", "Weight", "Cost", "Purchases"), sum) %>%
summarise_at(c(Length_LeapYear == "Length", Height_LeapYear == "Height"), ~sum(.[LeapYear==1])) %>%
summarise_at(c(Height_LeapYear_Weekend == "Height", Cost_LeapYear_Weekend == "Cost"), ~sum(.[LeapYear==1 & Weekend ==1])) %>%
summarise(Purchases_Weekend = sum(Purchases)) %>%
group_by(Color)
最终,我觉得必须有一种方法可以将这些不同条件的总和中的每一个都放入一个 summarise_at() 调用中。我也不确定对列(周末和闰年)进行有条件求和然后从最终表中省略这些列的最佳实践。因此,我们也将不胜感激。
作为记录,我确实知道我可以通过长时间调用 summarise() 来执行这些操作,在其中我单独调整每个派生列。 然而,在实践中,我的数据集比这宽得多,尝试通过对类似条件进行分组来压缩数据操作更有意义。
【问题讨论】:
-
查看我编辑的答案,希望它能达到目的。
标签: r dplyr conditional-statements tidyverse data-manipulation