I have an array and want to build a loop which averages every second value starting at the first value of the array and after the first round the loop should start with the second value of the array.
For example:
3,6,18,10,2
The result should be:
7.666,8,10
for 7.6666= (3+18+2)/3
for 8= (6+10)/2
for 10=(18+2)/2
Thanks in advance
Are you looking for something like this?
x <- c(3,6,18,10,2)
n <- length(x)
sapply(seq_len(n-2), function(X) {
mean(x[seq(X, n, by=2)])
})
# [1] 7.666667 8.000000 10.000000
And then something more interesting, to earn @mnel's upvote ;)
n <- length(x)
m <- matrix(0, n, n-2)
ii <- row(m) - col(m)
m[ii >= 0 & !ii %% 2] <- 1
colSums(x * m)/colSums(m)
# [1] 7.666667 8.000000 10.000000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With