joshuaulrich / xts

Extensible time series class that provides uniform handling of many R time series classes by extending zoo.
http://joshuaulrich.github.io/xts/
GNU General Public License v2.0
220 stars 71 forks source link

rollmean fails when there are missing values in multi-column xts and k = nrow(x) #367

Open eguidotti opened 2 years ago

eguidotti commented 2 years ago

Description

The function rollmean fails when there are missing values in multi-column xts object and k = nrow(x).

Expected behavior

I'd expect that rollmean works also with missing values as in the example below

Minimal, reproducible example

library(xts)

n <- 10
x <- xts(1:n, order.by = Sys.Date() + 1:n)
xx <- cbind(x, x)
rollmean(xx, k = n) # -> works fine

xx[n, 1] <- NA # -> add a missing value
rollmean(xx, k = n) # -> fails

Session Info

R version 4.2.0 (2022-04-22)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS Monterey 12.2.1

Matrix products: default
LAPACK: /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices datasets  utils     methods   base     

other attached packages:
[1] xts_0.12.1 zoo_1.8-10

loaded via a namespace (and not attached):
[1] compiler_4.2.0  tools_4.2.0     grid_4.2.0      renv_0.15.4     lattice_0.20-45
joshuaulrich commented 2 years ago

Thanks for the report!

I also noticed that rollmean() is using align = "center" instead of align = "right" like rollapply.xts() does by default. That's because there isn't a rollmean.xts() method for the rollmean() generic to dispatch, so it dispatches to rollmean.zoo(), and it uses align = "center" by default. So we probably also need xts methods for 'rollmean', 'rollsum', 'rollmedian', and 'rollmax'.

eguidotti commented 2 years ago

That would be awesome!