SCM

Forum: help

Monitor Forum | Start New Thread Start New Thread
RE: calculating partial rolling averages with fill [ Reply ]
By: Achim Zeileis on 2021-06-23 09:46
[forum:49001]
I don't think that the 3 and 4 in those locations would make sense. You have specified align="center" so the two observations before (both of which are 1) and after (both of which are 1) are used together with the current observation yielding 5. So maybe you are looking for something different?

A simpler reproducible example is:

ones <- rep(c(1, NA, 1), c(3, 2, 5))
rollapply(ones, 5, sum, partial = 3)

Maybe you are looking for:

rollapply(!is.na(ones), 5, sum, partial = 3)

?

calculating partial rolling averages with fill [ Reply ]
By: Ilja Kocken on 2021-06-23 09:32
[forum:49000]
I have a dataset for which I would like to calculate rolling means (and some other rolling summaries) using partial, but I would also like to enable `fill = NA` so that the final vector will be the same length, and can be used inside a `dplyr::mutate` call.

``` r
library(tidyverse)
library(zoo)
#>
#> Attaching package: 'zoo'
#> The following objects are masked from 'package:base':
#>
#> as.Date, as.Date.numeric
dat <- tibble(x = 1:15, y = rnorm(15))

dat %>%
mutate(y = ifelse(x %in% c(4, 5), NA_real_, y)) %>%
mutate(rm = rollmean(y, k = 5, align = "center", partial = 3)) %>%
mutate(ones = ifelse(is.na(y), NA_real_, 1)) %>%
mutate(rn = rollapply(ones, width = 5, align = "center", partial = 3, fill = NA, FUN = sum))
#> # A tibble: 15 x 5
#> x y rm ones rn
#> <int> <dbl> <dbl> <dbl> <dbl>
#> 1 1 0.811 0.147 1 3
#> 2 2 0.211 NA 1 NA
#> 3 3 -0.582 NA 1 NA
#> 4 4 NA NA NA NA
#> 5 5 NA NA NA NA
#> 6 6 -1.19 NA 1 NA
#> 7 7 -1.56 NA 1 NA
#> 8 8 0.115 -0.833 1 5 # <-- I want this to be 3
#> 9 9 -0.868 -0.517 1 5 # and this to be 4
#> 10 10 -0.659 -0.389 1 5
#> 11 11 0.383 -0.0519 1 5
#> 12 12 -0.914 0.196 1 5
#> 13 13 1.80 0.120 1 5
#> 14 14 0.372 0.0546 1 4
#> 15 15 -1.04 0.377 1 3
```

<sup>Created on 2021-06-23 by the [reprex package](https://reprex.tidyverse.org) (v2.0.0)</sup>

in the docs it says that if k is a scalar, fill = NA and partial are mutually exclusive. Is this necessary? Is there any way to compute the N of observations that are used for the rolling function?

Thanks to:
Vienna University of Economics and Business Powered By FusionForge