Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rollapply with expanding window in R

Let’s say I have a simple toy vector in R like:

x = seq(1:10);x
 [1]  1  2  3  4  5  6  7  8  9 10

I want to use the rollapply function from zoo package but in a different way.Rollapply calculates a function from a vector x with width argument to be a rolling window.I want instead of rolling to be expanding.There is similar question here and here but they don’t help me with my problem.

For example what I want to calculate the sum of the first observations of vector x and then expand the window but by 2.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Doing so I did :

rollapplyr(x, seq_along(x) ,sum,by=2,partial = 5,fill=NA)
 [1] NA NA NA NA 15 21 28 36 45 55

or replace the NA’s

na.locf0(rollapplyr(x, 5 ,sum,by=2,partial = 5,fill=NA))
[1] NA NA NA NA 15 15 25 25 35 35

But what I ideally want as a result is:

 [1] NA NA NA NA 15 15 28 28 45 45

Imagine that my dataset is huge (contains 2500 time series observations) and the function is some econometric – statistical model not a simple one like the sum that I use here.

How can I do it? Any help ?

>Solution :

x <- seq(10)

expandapply <- function(x, start, by, FUN){
  # set points to apply function up to
  checkpoints <- seq(start, length(x), by)
  # apply function to all windows
  vals <- sapply(checkpoints, function(i) FUN(x[seq(i)]))
  # fill in numeric vector at these points (assumes output is numeric)
  out <- replace(rep(NA_real_, length(x)), checkpoints, vals)
  # forward-fill the gaps
  zoo::na.locf(out, na.rm = FALSE)
}


expandapply(x, start = 5, by = 2, FUN = sum)
#>  [1] NA NA NA NA 15 15 28 28 45 45

Created on 2022-03-13 by the reprex package (v2.0.1)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading