gpt4 book ai didi

sql - 基 R : Aggregate and sum by two columns

转载 作者:行者123 更新时间:2023-12-04 10:12:48 26 4
gpt4 key购买 nike

我正在尝试使用聚合函数来实现与 SQL 查询相同的结果:

查询语句:

sqldf(" SELECT
PhotoID,
UserID,
SUM(Points) AS PhotoTotalPoints
FROM Photos
GROUP BY PhotoId, UserId")
116 186 rows.

R基础:
aggregate(x = Photos["Points"]
, by = Photos[c("PhotoId","UserId")]
, FUN = sum
)
114 950 rows.

使用 dplyr:
Photos %>%
group_by(PhotoId,UserId) %>%
summarise(sum = sum(Points))
116 186 rows.

我是 R 的新手。试图以多种方式解决它,但在文档中找不到任何解释。我错过了什么?

最佳答案

如果有 NA分组列之一中的元素,如果有 NA,默认情况下是 aggregate删除该行。为了防止这种情况,我们可以使用 na.action = NULL

aggregate(Points~ PhotoId + UserId
, FUN = sum, na.rm = TRUE, na.action = NULL
)

或者可能是一些未使用的组合被 drop = TRUE 丢弃的情况。对于 data.frame 方法
aggregate(x = Photos["Points"]
, by = Photos[c("PhotoId","UserId")]
, FUN = sum, na.rm = TRUE, drop = FALSE
)

关于sql - 基 R : Aggregate and sum by two columns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61240380/

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