lurodrig
lurodrig

Reputation: 99

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!

Upvotes: 2

Views: 3389

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269644

Here are two approaches:

1) Note that it is not that rollapply is giving 0 but that sum(x, na.rm = TRUE) is giving 0. The function sum(x, na.rm = TRUE) is not really what is desired here.

Instead, provide a version of sum that works in the way needed, i.e. it returns NA when the input is entirely NA values and returns sum(x, na.rm = TRUE) otherwise.

sum_na <- function(x) if (all(is.na(x))) NA else sum(x, na.rm = TRUE)
rollapplyr(z, 3, sum_na)

2) Alternately, use your code and fix it up afterwards by replacing any position that was all NA with an NA:

zz <- rollapplyr(z, 3, sum, na.rm = TRUE)
zz[rollapply(is.na(z), 3, all)] <- NA

giving:

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

Upvotes: 1

Rentrop
Rentrop

Reputation: 21497

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 

Upvotes: 0

Related Questions