Question Details

No question body available.

Tags

r dplyr moving-average

Answers (3)

Accepted Answer Available
Accepted Answer
September 17, 2025 Score: 6 Rep: 11,823 Quality: Expert Completeness: 60%

From help(zoo::rollapply):

partial
logical or numeric. If FALSE (default) then FUN is only applied when all indexes of the rolling window are within the observed time range. If TRUE, then the subset of indexes that are in range are passed to FUN. A numeric argument to partial can be used to determin the minimal window size for partial computations. See below for more details.

e.g.

data.frame(date = seq.Date(from='2025-01-01', to='2025-01-10'), value = 1:10) |>
  transform(valueroll = zoo::rollapply(
    value, width=5, FUN=mean, fill=NA, align='right', partial=TRUE))

gives

         date value valueroll
1  2025-01-01     1        1.0
2  2025-01-02     2        1.5
3  2025-01-03     3        2.0
4  2025-01-04     4        2.5
5  2025-01-05     5        3.0
6  2025-01-06     6        4.0
7  2025-01-07     7        5.0
8  2025-01-08     8        6.0
9  2025-01-09     9        7.0
10 2025-01-10    10        8.0

Note

Edit to add session info, see comments below this answer.

> sessionInfo()
R version 4.5.0 (2025-04-11)
Platform: aarch64-apple-darwin20
Running under: macOS Sequoia 15.2

Matrix products: default BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib LAPACK: /Library/Frameworks/R.framework/Versions/4.5-arm64/Resources/lib/libRlapack.dylib; LAPACK version 3.12.1

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

time zone: Europe/Berlin tzcode source: internal

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

loaded via a namespace (and not attached): [1] zoo
1.8-14 compiler4.5.0 tools4.5.0 grid4.5.0 lattice0.22-6
September 17, 2025 Score: 3 Rep: 21,710 Quality: Medium Completeness: 60%

You can create a "sub-frame" with slider::slidedfr() with all your windowed calculations; mutate(), when called without a name, unnests it to columns:

tibble::tibble(date = seq.Date(from = "2025-01-01", to = "2025-01-10"), value = 1:10) |> dplyr::mutate( slider::slide
dfr( value, .f = \(x) data.frame(meanroll = mean(x), sumroll = sum(x), sdroll = sd(x)), .before = 4 ) ) #> # A tibble: 10 × 5 #> date value meanroll sumroll sdroll #> #> 1 2025-01-01 1 1 1 NA #> 2 2025-01-02 2 1.5 3 0.707 #> 3 2025-01-03 3 2 6 1 #> 4 2025-01-04 4 2.5 10 1.29 #> 5 2025-01-05 5 3 15 1.58 #> 6 2025-01-06 6 4 20 1.58 #> 7 2025-01-07 7 5 25 1.58 #> 8 2025-01-08 8 6 30 1.58 #> 9 2025-01-09 9 7 35 1.58 #> 10 2025-01-10 10 8 40 1.58
September 17, 2025 Score: 3 Rep: 105,804 Quality: Medium Completeness: 70%

You can define a customized moving average function mva

  • using cumsum + stats::filter

mva