1

I want to calculate meas of three consecutive variables enter image description herea vector.

Ex: Vec<-rep(1:10)

I would like the output to be like the screenshot below:

mad
  • 167
  • 1
  • 9

2 Answers2

1

We can create a grouping variable using gl and then get the mean with ave

 ave(Vec, as.numeric(gl(length(Vec), 3, length(Vec))))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Can it be made so that the length will be 5 instead of 15? Like: 2, 5, 8, 11, 14? – mad Oct 10 '15 at 16:48
  • @mad The `Vec <- 1:10` If you meant to get the mean of 5 consecutive values, change the `gl` to `gl(length(Vec), 5, length(Vec))` – akrun Oct 10 '15 at 16:51
1

You can create the following function to calculate means by groups of 3 (or any other number):

   f <- function(x, k=3) 
     {
       for(i in seq(k,length(x),k)) 
         x[(i/k)] <- mean(x[(i-k+1):i]) 
      return(x[1:(length(x)/k)])
   }

f(1:15) [1] 2 5 8 11 14

Acoustesh
  • 160
  • 3