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

______________________________________________
[EMAIL PROTECTED] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html

Reply via email to