> library(zoo)
Attaching package: ‘zoo’
The following objects are masked from ‘package:base’:
as.Date, as.Date.numeric
> z =c(NA,NA,1,2,3)
> rollapply(z,width=2,max,fill=NA,align="r",na.rm=T)
[1] NA -Inf 1 2 3
Warning message:
In FUN(data[posns], ...) : no non-missing arguments to max; returning -Inf
>
I do understand that the max of an empty set is -Inf. This is mentioned in ?max.
That explains why the rollapply at the second position is -Inf. I think that at the second position, we remove the 2 NA's on position 1 and 2, and we are left with an empty set and hence the max is -Inf.
My query is : Why is the rollapply at the first position NA?
Should it also not be -Inf? Can someone please explain? What is the rationale behind it ?
CodePudding user response:
I think I misunderstood the fill argument. It replaces the NA's in the result of rollapply.
> rollapply(z,width=2,max,fill=200,align="r",na.rm=T)
[1] 200 -Inf 1 2 3
Warning message:
In FUN(data[posns], ...) : no non-missing arguments to max; returning -Inf
and not in the input to rollapply.
I was thinking that it would first compute the max at the first position by filling in the "imaginary data" at the "0th position" by NA and then do a max (which would be -Inf).
CodePudding user response:
If there are fewer than 2 points available then it does not run max
at all but rather outputs the fill
value which is NA. If -Inf
were wanted then specify fill = -Inf
or alternately use partial=TRUE
which will use max
even if there are less than 2 points available.
library(zoo)
z <- c(NA, NA, 1, 2, 3)
rollapplyr(z, 2, max, na.rm = TRUE, fill = -Inf)
## [1] -Inf -Inf 1 2 3
rollapplyr(z, 2, max, na.rm = TRUE, partial = TRUE)
## [1] -Inf -Inf 1 2 3
Note that we can avoid the warnings from max
by additionally passing -Inf
to max
:
rollapplyr(z, 2, max, -Inf, na.rm = TRUE, fill = -Inf)
## [1] -Inf -Inf 1 2 3