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
  • 157
  • 1
  • 8

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
  • 789,025
  • 32
  • 460
  • 575
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