Right alignment. For the following it computes the result as y[i] = x[i-2] + x[i-1] + x[i]:
x <- 1:10
y <- rollapply(x, 3, sum, align = "right", fill = NA)
y
## [1] NA NA 6 9 12 15 18 21 24 27
The calculations are:
rollapply(x, 3, function(x) paste(x, collapse = "+"), align = "right", fill = NA)
## [1] NA NA "1+2+3" "2+3+4" "3+4+5" "4+5+6" "5+6+7"
## [8] "6+7+8" "7+8+9" "8+9+10"
An equivalent way of specifying this is in terms of offsets. That is, feed the element 2 positions back, 1 position back and the current position to sum
:
rollapply(x, list(c(-2, -1, 0)), sum, fill = NA) # same as align = "right"
Center alignment. For the following it computes the result as y[i] = x[i-1] + x[i] + x[i+1]:
x <- 1:10
y <- rollapply(x, 3, sum, align = "center", fill = NA)
y
## [1] NA 6 9 12 15 18 21 24 27 NA
The calculations are:
rollapply(x, 3, function(x) paste(x, collapse = "+"), align = "center", fill = NA)
## [1] NA "1+2+3" "2+3+4" "3+4+5" "4+5+6" "5+6+7" "6+7+8"
## [8] "7+8+9" "8+9+10" NA
An equivalent way to specify this is via offsets. That is feed the prior, current and next value to sum:
rollapply(x, list(c(-1, 0, 1)), sum, fill = NA) # same as align = "center"
Left alignment. For the following it computes the result as y[i] = x[i] + x[i+1] + x[i+2]:
x <- 1:10
y <- rollapply(x, 3, sum, align = "left", fill = NA)
y
## [1] 6 9 12 15 18 21 24 27 NA NA
The calculations are:
rollapply(x, 3, function(x) paste(x, collapse = "+"), align = "left", fill = NA)
## [1] "1+2+3" "2+3+4" "3+4+5" "4+5+6" "5+6+7" "6+7+8" "7+8+9"
## [8] "8+9+10" NA NA
This can also be specified in terms of offsets. That is use the current, next and position after next to feed to sum
:
rollapply(x, list(c(0, 1, 2)), sum, fill = NA) # same as align = "left"
Note
Note that the right and center alignment can be written more compactly as:
y <- rollapplyr(x, 3, sum, fill = NA) # note r on the end to denote right
y <- rollapply(x, 3, sum, fill = NA) # no align specified so center