lurodrig lurodrig - 2 months ago 8
R Question

rollapply na.rm = TRUE giving 0 values instead of NA's

I have a simple question, that I can't seem to find the answer to on google, stackoverflow or stackexchange. I am currently working with the example of

rollapply
to find the sum of some values that contain NA's. For example:

z <- zoo(c(NA, NA, NA, NA,2, 3, 4, 5, NA))
rollapply(z, 3, sum, na.rm = TRUE, align = "right")


This outputs:

3 4 5 6 7 8 9
0 0 2 5 9 12 9


This looks good, however, there are two times where there are 3 NA's in a row. The sum feature exchanges NA's to 0's. Unfortunately, that won't work with the data I'm going to work with since 0 is a meaningful value. Is there a way to replace the 0's with NA's again?

I'm looking for an output as below:

3 4 5 6 7 8 9
NA NA 2 5 9 12 9


Thank you in advance!

Answer

You can do the following (even though not very nice)

require(zoo)
z <- zoo(c(NA, NA, NA, NA,2, 3, 4, 5, NA))
tmp <- rollapply(z, 3, sum, na.rm = TRUE, align = "right")

tmp[is.na(z)[-2:-1] & tmp == 0] <- NA
tmp

so you assign NA wherever z is na and there is a NA produced by rollapply

which gives you:

> tmp
 3  4  5  6  7  8  9 
NA NA  2  5  9 12  9 
Comments