Skip to content

Commit 637ff68

Browse files
committed
Handle 'width' when it's a numeric vector
rollapply.xts() only supports 'width' when it's a scalar, while rollapply.zoo() supports 'width' when it's a vector of multiple values. Support this in rollapply.xts() by converting 'data' to zoo, calling rollapply() on the zoo object, and converting the result back to xts. Thanks to James Hirschorn (@quantitative-technologies) for the report, and to @npschweizer for the nudge to fix. Fixes #290.
1 parent bfec4d1 commit 637ff68

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

R/rollapply.xts.R

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,21 @@ rollapply.xts <- function(data, width, FUN, ..., by=1, by.column=TRUE,
2222
fill=if(na.pad) NA, na.pad=TRUE, partial=TRUE,
2323
align=c("right","center","left")) {
2424

25+
# handle width when it has multiple elements
26+
if (length(width) > 1) {
27+
align. <- match.arg(align)
28+
result <-
29+
rollapply(as.zoo(data), width, FUN, ..., by = by,
30+
by.column = by.column, fill = fill,
31+
partial = partial, align = align.)
32+
33+
result <- as.xts(result)
34+
return(result)
35+
} else {
36+
width <- as.integer(width)
37+
stopifnot(width > 0, width <= NROW(data))
38+
}
39+
2540
if (!missing(na.pad)) {
2641
warning("na.pad argument is deprecated")
2742
}
@@ -42,8 +57,6 @@ rollapply.xts <- function(data, width, FUN, ..., by=1, by.column=TRUE,
4257

4358
nr <- NROW(data)
4459
nc <- NCOL(data)
45-
width <- as.integer(width)[1]
46-
stopifnot( width > 0, width <= nr )
4760

4861
## process alignment
4962
align <- match.arg(align)

inst/tinytest/test-rollapply.R

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
info_msg <- "test rollapply.xts() handles multi-element 'width'"
2+
x <- .xts(1:6, 1:6)
3+
rsum <- rollapply(x, width = 1:6, FUN = sum)
4+
csum <- cumsum(x)
5+
expect_equal(rsum, csum, info = info_msg)

0 commit comments

Comments
 (0)