[R] functions for special na handling?
Sundar Dorai-Raj
sundar.dorai-raj at PDF.COM
Mon Oct 25 22:49:02 CEST 2004
Sundar Dorai-Raj wrote:
>
>
> Robert Sams wrote:
>
>> hi,
>>
>> i need a function that can replace na's in univariate ts objects with
>> a value interpolated linearly using the adjacent non-na values. for
>> example, the function i need (myfun) would do the following
>>
>>
>>> x <- ts(10,11.4,NA,12,9.7)
>>> y <- myfun(x)
>>> y
>>
>>
>> 10 11.4 11.7 12 9.7
>>
>> i can code an na.action method myself to accomplish this, but has
>> someone else already coded routines of this nature?
>>
>> many thanks,
>> robert
>>
>>
>> Robert Sams
>
>
> Hi Robert,
> Will the following do?
>
> na.approx <- function(x) {
> na <- is.na(x)
> if(all(!na)) return(x)
> i <- seq(along = x)
> x[na] <- approx(i[!na], x[!na], i[na])$y
> x
> }
>
> > x <- c(10,11.4,NA,12,9.7)
> > na.approx(x)
> [1] 10.0 11.4 11.7 12.0 9.7
>
>
One other note: na.approx as written above will return NA if the first
or last element of your vector is missing. See ?approx on how to change
this behaviour.
--sundar
More information about the R-help
mailing list