在 R 中应用分组向量的有效方法[重复]

问题描述 投票:0回答:2

假设我有一些分组向量形式的分组信息:

group = c(1,1,2,2,3,3,3)

所以这就是说我有三组:两组大小为 2 的组和一组大小为 3 的组。现在假设我有一个向量(我添加了随机数)

x = c(1.5, 3.1, 5.4, -4.5, 2.2, 4.4, 1.1)

R 中是否有一种有效的方法来循环该向量并在组内应用某些函数?

例如,每组内的求和,使用 for 循环将是:

sums = rep(0,3)
for (i in 1:3){
grp_ids = which(group == i)
sums[i] = sum(x[grp_ids])
}

有更简单的方法吗?

r vector
2个回答
0
投票

您可以使用 {dplyr} 中的

group_by
:

library(dplyr)

group = c(1, 1, 2, 2, 3, 3, 3)
x = c(1.5, 3.1, 5.4, -4.5, 2.2, 4.4, 1.1)

df <- data.frame(group, x)

result <- df %>%
  group_by(group) %>%
  summarize(sums = sum(x))

> print(result)
# A tibble: 3 × 2
  group  sums
  <dbl> <dbl>
1     1   4.6
2     2   0.9
3     3   7.7

0
投票

对于性能,请查看

collapse
包。

library(collapse)

# efficient group summing
fsum(x, group)
#>   1   2   3 
#> 4.6 0.9 7.7
# apply a generic function
BY(x, group, min)
#>    1    2    3 
#>  1.5 -4.5  1.1
# apply a list of functions
collap(x, group, list(sum, prod, min, max))
#>   group sum.X  prod.X min.X max.X
#> 1     1   4.6   4.650   1.5   3.1
#> 2     2   0.9 -24.300  -4.5   5.4
#> 3     3   7.7  10.648   1.1   4.4
© www.soinside.com 2019 - 2024. All rights reserved.