The average value in the array

I have an array and you want to build a cycle that averages every second value, starting from the first value of the array, and after the first round, the cycle should start from the second value of the array.

For instance:

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 

Thank you in advance

+4
source share
2 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 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 
+6
source

Another for lovers:

 rev(filter(rev(x), 0:1, "r") / filter(rep(1, length(x)), 0:1, "r")) # [1] 7.666667 8.000000 10.000000 10.000000 2.000000 
+5
source

All Articles