用一个例子来最好地解释这个问题.

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在这种情况下没有得到应有的使用.

推荐答案

您可以使用cur_group()来获取当前的群信息.然后从那里提取ID

df |> summarise(mean(x) * cur_group()$id, .by=id)
#   id mean(x) * cur_group()$id
# 1  1                      1.5
# 2  2                      7.0

如果您有更多的分组列,您可以

df <- data.frame(alpha = c(7,7,23,23), beta=c(-1,-1,3,3), x = 1:4)

df |> group_by(alpha, beta) |> summarise(mean(x) * cur_group()$alpha)
#  alpha  beta `mean(x) * cur_group()$alpha`
#   <dbl> <dbl>                         <dbl>
# 1     7    -1                          10.5
# 2    23     3                          80.5
df |> group_by(alpha, beta) |> summarise(mean(x) * cur_group()$beta)
#   alpha  beta `mean(x) * cur_group()$beta`
#   <dbl> <dbl>                        <dbl>
# 1     7    -1                         -1.5
# 2    23     3                         10.5

R相关问答推荐

如何按照特定顺序拆分字符?

通过Plotly绘制线串几何形状的3D图

在ggplot的注释表格中突出显示最大值

如果列中存在相同的字符串,则对行值进行总和

如何根据条件计算时差(天)

r替换lme S4对象的字符串的一部分

derrr mutate case_when grepl不能在R中正确返回值

使用case_match()和char数组重新编码值

我不能在docker中加载sf

多个过滤器内的一个盒子在仪表板Quarto

如何读取CSV的特定列时,给定标题作为向量

按多列统计频次

R -在先前group_by级别汇总时获取最大大小子组的计数

基于数据集属性将科分配给物种

我如何使用循环来编写冗余的Rmarkdown脚本?

层次树图的数据树

按组跨多列创建伪变量

SHILINY中DT列的条件着色

R预测包如何处理ARIMA(Auto.arima函数)中的缺失值

R try Catch in the loop-跳过缺少的值并创建一个DF,显示跳过的内容