计算R中无序向量各组的平均数。

问题描述 投票:-1回答:4

我的问题可能很简单!

我有一个 无序 我想把这个变量剪掉。k 然后计算每组数值的平均值。

vec = c(1:10,1:5,2:6)
mean(vec[1:4])
mean(vec[5:8])
mean(vec[9:12])
mean(vec[13:16])
mean(vec[17:20])

先谢谢你的帮助!

r vector mean
4个回答
1
投票

分成5组。

lapply(split(vec, sort(vec%%5)), mean)
$`0`
[1] 2.5

$`1`
[1] 6.5

$`2`
[1] 5.5

$`3`
[1] 3.5

$`4`
[1] 4.5

1
投票

另一种方法是用 aggregate

vec <- c(1:10,1:5,2:6)

mystep <- 4

bins <- rep(1:ceiling(length(vec)/mystep), each = mystep)
bins <- bins[1:length(vec)]  # removes any "overflow" values due to ceiling
xy <- data.frame(vec, bins)

aggregate(vec ~ bins, data = xy, FUN = mean)

  bins vec
1    1 2.5
2    2 6.5
3    3 5.5
4    4 3.5
5    5 4.5

0
投票
vec = c(1:10,1:5,2:6)

# get quartiles, quantiles, or any prob
q <- quantile(vec, c(0.25,.5,.75, 1) )  

# get the means
lapply(q, function(x){mean(vec[vec<=x])})

    $`25%`
[1] 1.6

$`50%`
[1] 2.636364

$`75%`
[1] 3.5

$`100%`
[1] 4.5

0
投票

感谢这个 回答我找到了一个解决方案

vec = c(1:10,1:5,2:6)
aa= split(vec, floor(5 * seq.int(0, length(vec) - 1) / length(vec)))
lapply(aa, mean)
 # To be compared:
mean(vec[1:4])
mean(vec[5:8])
mean(vec[9:12])
mean(vec[13:16])
mean(vec[17:20])
© www.soinside.com 2019 - 2024. All rights reserved.