Here is a list.
1 2 3 4 5 6 7 8 9 10.
I would like to calculate average of every three consecutive elements. For instance, output would be NA NA 2 3 4 5 6 7 8 9.
How to do this?
Regards
You could try ?embed and ?rowMeans:
v <- 1:10
m <- embed(v, 3)
m
# [,1] [,2] [,3]
#[1,] 3 2 1
#[2,] 4 3 2
#[3,] 5 4 3
#[4,] 6 5 4
#[5,] 7 6 5
#[6,] 8 7 6
#[7,] 9 8 7
#[8,] 10 9 8
rowMeans(m)
# 2 3 4 5 6 7 8 9
EDIT: Another solution would be ?filter:
filter(x=v, filter=rep(1/3, 3), sides=1)
# Time Series:
# Start = 1
# End = 10
# Frequency = 1
# [1] NA NA 2 3 4 5 6 7 8 9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With