CptNemo
CptNemo

Reputation: 6755

R: How to manage heading and trailing NAs when using rollmean()

I have this vector

vec <- c(NA, 1, 2, 3, 4, NA)

for which I wish to calculate a rollmean of a window of size 3 aligned to the right (that is, if I understand correctly looking backwards)

The expected rolling mean of my vector would be

# [1] NA NA NA  2  3  NA #

and yet if I do

rollmean(vec, 3, align='right', fill=NA)

I obtain

# [1] NA NA NA NA NA NA

Upvotes: 2

Views: 669

Answers (1)

vck
vck

Reputation: 837

You can use apply function instead.

rollapply(vec,3,mean,fill=NA,align="right")
[1] NA NA NA  2  3 NA

Upvotes: 3

Related Questions