timriffe / DemoTools

Tools for the evaluation, adjustment, and standardization of demographic data
https://timriffe.github.io/DemoTools
Other
61 stars 31 forks source link

mav doesn't work well with even orders #127

Closed peterdavjohnson closed 4 years ago

peterdavjohnson commented 4 years ago

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)

} }

peterdavjohnson commented 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)
  }
}
timriffe commented 4 years ago

fixed in heapingfixes branch