Skip to content
Back to formatted view

Raw Message

Message-ID: <417D63E6.7040305@pdf.com>
Date: 2004-10-25T20:36:54Z
From: Sundar Dorai-Raj
Subject: functions for special na handling?
In-Reply-To: <E585EABA11227445B918BFB74C1A4D36015958@sanctum01.sanctumfi.com>

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


--sundar