SCM

Forum: open-discussion

Monitor Forum | Start New Thread Start New Thread
RE: Bug in rollmedian [ Reply ]
By: Achim Zeileis on 2012-08-25 08:53
[forum:14108]
rollmedian() requires input of an _odd_ k, see ?rollmedian for details. It does not have any rounding logic at all, it works only if k is odd.

You did not supply such an odd k which then gets changed by runmed() which is internally used. and then results in a verbose error message. So I don't see a bug here.

If you want to compute a rolling median with an even k, use rollapply(z, k, median).

Bug in rollmedian [ Reply ]
By: Corwin Joy on 2012-08-24 17:34
[forum:14106]
It looks like rollmedian has some incorrect rounding logic when an invalid window is passed to the function.
To reproduce:
1. Create a series, call it mdv, with 126 values.
2. Set k = 126
3. Call rollmedian via:
rollmedian(mdv, k, align = "right", na.pad=T)

Get error
Error in NextMethod("[<-") : replacement has length zero
In addition: Warning messages:
1: In runmed(x, k, ...) : 'k' must be odd! Changing 'k' to 127
2: In runmed(x, k, ...) : 'k' is bigger than 'n'! Changing 'k' to 125

Enter a frame number, or 0 to exit

1: rollmedian(mdv, k, align = "right", na.pad = T)
2: rollmedian.default(mdv, k, align = "right", na.pad = T)
3: coredata(rollmedian(zoo(x), k, fill = fill, align = align, ...))
4: rollmedian(zoo(x), k, fill = fill, align = align, ...)
5: rollmedian.zoo(zoo(x), k, fill = fill, align = align, ...)
6: do.call("merge", c(lapply(1:NCOL(x), function(i) {
7: lapply(1:NCOL(x), function(i) {
8: FUN(1:2[[1]], ...)
9: rollmedian(x[, i, drop = TRUE], k, fill = fill, align = align, ...)
10: rollmedian.zoo(x[, i, drop = TRUE], k, fill = fill, align = align, ...)
11: `[<-`(`*tmp*`, ix, value = numeric(0))
12: `[<-.zoo`(`*tmp*`, ix, value = numeric(0))
13: NextMethod("[<-")

From the above trace it looks like two different k values are used by the routine. k = 127 and k = 125.
Recommended fix, always round k down to the nearest odd number. For example:
n = nrow(mdv)
k = n - (1-n%%2) # Round down to nearest odd number


Thanks to:
Vienna University of Economics and Business Powered By FusionForge