I want to calculate meas of three consecutive variables a vector.
Ex: Vec<-rep(1:10)
I would like the output to be like the screenshot below:
I want to calculate meas of three consecutive variables a vector.
Ex: Vec<-rep(1:10)
I would like the output to be like the screenshot below:
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))))
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