gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:59:17 24 4
gpt4 key购买 nike

我有这个数据集:

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,它也满足 hour >= 20 的条件,但它在输出数据集“f”中显示为 0。

我在这里做错了什么?

最佳答案

以下是可行的:

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 按顺序工作,因此 amount 在到达 amount_after_8 时已经是汇总输出。

关于r - 总结使用 dplyr 给出错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51812182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com