总结使用dplyr给出错误的结果

时间:2018-08-12 19:32:48

标签: r group-by dplyr

我有这个数据集:

structure(list(id = c(2004938L, 2107410L, 2119255L, 2129457L, 
2141169L, 2172051L), date = structure(c(17725, 17732, 17733, 
17734, 17734, 17736), class = "Date"), hour = c(20, 22, 18, 12, 
21, 22), store_name = c("Www Cigarsindia In India S Largest And Trusted Online Cigar Store Since 1998", 
"Www Cigarsindia In India S Largest And Trusted Online Cigar Store Since 1998", 
"Www Cigarsindia In India S Largest And Trusted Online Cigar Store Since 1998", 
"Www Cigarsindia In India S Largest And Trusted Online Cigar Store Since 1998", 
"Www Cigarsindia In India S Largest And Trusted Online Cigar Store Since 1998", 
"Www Cigarsindia In India S Largest And Trusted Online Cigar Store Since 1998"
), area = c("Indiranagar, EGL", "Indiranagar, EGL", "Indiranagar, EGL", 
"Indiranagar, EGL", "Indiranagar, EGL", "Indiranagar, EGL"), 
    amount = c(900, 2400, 2700, 380, 150, 100)), row.names = c(6264L, 
10841L, 11355L, 11892L, 12348L, 13570L), class = "data.frame")

我们称之为“ e”。

我想总结如下:

f = e %>%
dplyr::group_by(date, store_name, area) %>%
dplyr::summarize(amount = sum(amount, na.rm = TRUE), amount_after_8 = sum(amount[hour >= 20], na.rm = TRUE))

这将输出“ f”表示为:

structure(list(date = structure(c(17725, 17732, 17733, 17734, 
17736), class = "Date"), store_name = c("Www Cigarsindia In India S Largest And Trusted Online Cigar Store Since 1998", 
"Www Cigarsindia In India S Largest And Trusted Online Cigar Store Since 1998", 
"Www Cigarsindia In India S Largest And Trusted Online Cigar Store Since 1998", 
"Www Cigarsindia In India S Largest And Trusted Online Cigar Store Since 1998", 
"Www Cigarsindia In India S Largest And Trusted Online Cigar Store Since 1998"
), area = c("Indiranagar, EGL", "Indiranagar, EGL", "Indiranagar, EGL", 
"Indiranagar, EGL", "Indiranagar, EGL"), amount = c(900, 2400, 
2700, 530, 100), amount_after_8 = c(900, 2400, 0, 0, 100)), row.names = c(NA, 
-5L), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), vars = c("date", 
"store_name"), drop = TRUE)

现在此输出是错误的,因为“ e”中的第5行包含一个值150,它也满足小时> = 20的条件,但是在输出数据集“ f”中显示为0。

我在这里做什么错了?

1 个答案:

答案 0 :(得分:2)

以下将起作用:

e %>%
  dplyr::group_by(date, store_name, area) %>%
  dplyr::summarize(
  amount_after_8 = sum(amount[hour >= 20], na.rm = TRUE), amount = sum(amount, na.rm = TRUE)
)

问题是summarize按顺序工作,因此amountamount_after_8时已经是汇总输出。