4

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

thelatemail
  • 91,185
  • 12
  • 128
  • 188
burton030
  • 405
  • 4
  • 8
  • 23

2 Answers2

6

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
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
  • Too quick. I shouldn't have spent time alerting the OP to their basic arithmetic error. – mnel Dec 05 '12 at 00:20
  • 1
    @mnel -- I did treat this one as basically a speed typing test. Maybe I'll see if I can come up with something more elegant/interesting. – Josh O'Brien Dec 05 '12 at 00:22
5

Another one for the 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
flodel
  • 87,577
  • 21
  • 185
  • 223
  • `filter` always seems like voodoo to me and the help file goes over my head. Is there a `filter() for dummies` available? – thelatemail Dec 05 '12 at 02:46
  • @thelatemail, I have the same problem. And extra-points for explanations about how to think about `Reduce` and `Filter`. I occasionally get them to work, but I fell flat on my face when trying it on this one. Post a question. I'll vote for it. – IRTFM Dec 05 '12 at 04:55