Running sum in specified window of numeric vector.

sum_run(
  x,
  k = integer(0),
  lag = integer(1),
  idx = integer(0),
  at = integer(0),
  na_rm = TRUE,
  na_pad = FALSE
)

Arguments

x

numeric vector which running function is calculated on

k

(integer`` vector or single value)\cr Denoting size of the running window. If kis a single value then window size is constant for all elements, otherwise iflength(k) == length(x)` different window size for each element.

lag

(integer vector or single value)
Denoting window lag. If lag is a single value then window lag is constant for all elements, otherwise if length(lag) == length(x) different window size for each element. Negative value shifts window forward.

idx

(integer, Date, POSIXt)
Optional integer vector containing sorted (ascending) index of observation. By default idx is index incremented by one. User can provide index with varying increment and with duplicated values. If specified then k and lag are depending on idx. Length of idx have to be equal of length x.

at

(integer, Date, POSIXt, character vector)
Vector of any size and any value defining output data points. Values of the vector defines the indexes which data is computed at.

na_rm

logical single value (default na_rm = TRUE) - if TRUE sum is calculating excluding NA.

na_pad

(logical single value)
Whether incomplete window should return NA (if na_pad = TRUE) Incomplete window is when some parts of the window are out of range.

Value

sum numeric vector of length equals length of x.

Examples

set.seed(11)
x1 <- rnorm(15)
x2 <- sample(c(rep(NA, 5), rnorm(15)), 15, replace = TRUE)
k <- sample(1:15, 15, replace = TRUE)
sum_run(x1)
#>  [1] -0.5910311 -0.5644367 -2.0809898 -3.4436432 -2.2651540 -3.1993053
#>  [7] -1.8756997 -1.2507819 -1.2965049 -2.3006254 -3.1290587 -3.4774104
#> [13] -5.0157038 -5.2712690 -6.4212141
sum_run(x2, na_rm = TRUE)
#>  [1] -0.1876001 -0.1804413 -0.1962995  0.1562580 -0.6094426 -0.8324122
#>  [7] -0.8324122 -1.0200123 -1.0076853 -1.0005265 -0.9881996 -0.9758726
#> [13] -0.6233151 -0.6109881 -0.7985882
sum_run(x2, na_rm = FALSE)
#>  [1] -0.1876001 -0.1804413 -0.1962995  0.1562580 -0.6094426 -0.8324122
#>  [7]         NA         NA         NA         NA         NA         NA
#> [13]         NA         NA         NA
sum_run(x2, na_rm = TRUE, k = 4)
#>  [1] -0.1876001 -0.1804413 -0.1962995  0.1562580 -0.4218425 -0.6519709
#>  [7] -0.6361127 -1.1762703 -0.3982427 -0.1681143 -0.1557874  0.0441397
#> [13]  0.3843702  0.3895384  0.1896113