Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate average of every three consecutive elements

Tags:

r

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

like image 356
Sumit Avatar asked Jan 22 '26 03:01

Sumit


1 Answers

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
like image 93
sgibb Avatar answered Jan 23 '26 19:01

sgibb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!