Closed peterdavjohnson closed 4 years ago
Still getting my R-feet wet. The function above only is correct for n=10 (and odd values). I think the code should be
ma<- function(x, n = 5) {
if (n %% 2 == 1) { # odd as before
as.vector(stats::filter(x, rep(1 / n, n), sides = 2))
} else { # even...
temp <- as.vector(stats::filter(x, rep(1 / (2*n), n), sides = 1))
shift.vector(temp,shift=-n/2+1,fill=NA)+shift.vector(temp,shift=-n/2,fill=NA)
}
}
fixed in heapingfixes
branch
In order to center the moving average when the order is even, the best approach is to average the surrounding n-1 ages plus half of the next oldest and youngest ages. Here is a possible replacement function ma that will fix this. ma <- function(x, n = 5) { if (n %% 2 == 1) { # odd as before as.vector(stats::filter(x, rep(1 / n, n), sides = 2)) } else { # even... temp <- as.vector(stats::filter(x, rep(1 / (2*n), n), sides = 1)) shift.vector(temp,shift=-4,fill=NA)+shift.vector(temp,shift=-5,fill=NA)
} }