【问题标题】:R - How to use group by with customized calculation [duplicate]R - 如何通过自定义计算使用分组[重复]
【发布时间】:2020-11-20 08:34:13
【问题描述】:

假设我有以下示例数据:

ID Group Score
1 A 1
2 A 3
3 A 2
4 B 5
5 B 1
6 C 1
7 C 2
8 C 4
9 D 1
10 D 3

我想使用 group by 进行自定义计算:每个组内每个分数的平方和的平方根。

  • ID 是唯一的。 (每一行都是唯一的)
  • 有100+组
  • 计算基于变量“Score”
  • 每组中的行数各不相同

例如,在最终输出中,只有两列:

Group AdjustedScore
A        3.74         **Square root of (1+9+4)
B        5.09         **Square root of (25+1)
C        4.58         **Square root of (1+4+16)
......
......

如何在 R 中做到这一点?我不擅长 R,感谢您的帮助。

【问题讨论】:

    标签: r loops group-by square-root


    【解决方案1】:

    你可以使用:

    library(dplyr)
    df %>% group_by(Group) %>% summarise(Score = sqrt(sum(Score^2)))
    
    #  Group Score
    #  <chr> <dbl>
    #1 A      3.74
    #2 B      5.10
    #3 C      4.58
    #4 D      3.16
    

    在基础 R 中,您可以使用 aggregate

    aggregate(Score~Group, df, function(x) sqrt(sum(x^2)))
    

    或者data.table

    library(data.table)
    setDT(df)[, sqrt(sum(Score^2)), Group]
    

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 2017-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多