Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average of values in an array

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

like image 979
burton030 Avatar asked Dec 21 '22 12:12

burton030


1 Answers

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
like image 169
Josh O'Brien Avatar answered Jan 22 '23 17:01

Josh O'Brien