[R] Omitting NAs in aggregate.ts()

Waichler, Scott R Scott.Waichler at pnl.gov
Tue May 17 17:52:56 CEST 2005


> > I have a time series vector (not necessarily ts class) that has NAs
in it.
> > How can I omit the NAs when using aggregate.ts() to compute a
function 
> > on each window?  If there is at least one non-NA value in each
window, 
> > I'd like to proceed with evaluating the function; otherwise, I would

> > like NA returned.  I'm not wedded to aggregate.ts and don't need ts 
> > class if there is another fast, vectorized way to handle this.  Here

> > is what I am trying to do, with the invalid na.rm thrown in:
> > 
> > as.vector(aggregate.ts(x, ndeltat=24, FUN=min, na.rm=F))
> > 

> I don't know is the short answer, but if I had the data I 
> might have tried mymin <- function(x) min(x, na.rm = TRUE) 
> as.vector(aggregate.ts(x, ndeltat=24, FUN=mymin))


Thanks for the suggestions, and my apologies for not providing an
example and error messages.  Using a custom function for FUN in
aggregate.ts() is the way to go.  Here is a complete solution to my
problem:

> e <- c(2.3, 4.5, 6.2, 1.8)
> f <- c(2.3, NA, NA, NA)
>
> mymin <- function(x) {
+   if(length(x[!is.na(x)]) > 0) return(min(x, na.rm = TRUE))
+   else return(NA)
+ }
>
> as.vector(aggregate.ts(e, ndeltat=2, FUN=mymin))
[1] 2.3 1.8
> as.vector(aggregate.ts(f, ndeltat=2, FUN=mymin))
[1] 2.3  NA
>           

Scott Waichler
Pacific Northwest National Laboratory
scott.waichler at pnl.gov




More information about the R-help mailing list