用一个例子来最好地解释这个问题.
library(dplyr)
library(data.table)
df <- data.frame(
id = c(1,1,2,2),
x = 1:4
)
比方说,我们需要得到一个按组计算的平均值,再乘以组值.在data.table
中,这是直截了当和直观的.
> setDT(df)[, .(mean(x) * id), by=id]
id V1
1: 1 1.5
2: 2 7.0
然而,在dplyr
中,有一个警告和行重复.
> df |> group_by(id) |> summarise(mean(x) * id)
`summarise()` has grouped output by 'id'. You can override using the `.groups` argument.
# A tibble: 4 × 2
# Groups: id [2]
id `mean(x) * id`
<dbl> <dbl>
1 1 1.5
2 1 1.5
3 2 7
4 2 7
Warning message:
Returning more (or less) than 1 row per `summarise()` group was deprecated in dplyr 1.1.0.
ℹ Please use `reframe()` instead.
我意识到我可以通过增加unique()
的额外步长来消除重复,但我忍不住觉得dplyr
在这种情况下没有得到应有的使用.