我尝试使用聚合函数来获得与 SQL 查询相同的结果:
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
)
或者可能是使用 data.frame 方法的 drop = TRUE
删除一些未使用的组合的情况
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/