[R] Replacing NAs with interpolated values

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Wed Sep 5 17:18:59 CEST 2001


Torsten Hothorn <Torsten.Hothorn at rzmail.uni-erlangen.de> writes:

> > Hi there,
> > 
> > I've got this vector:
> > 
> > -84  -87  -90  -90  -89  -86 NA NA NA NA NA NA NA NA NA NA NA NA  -96 
> > -99 -100  -99  -96 -92  -89  -87  -87  -88  -90  -92  -94  -95  -96 
> > -97  -97  -97  -96  -95
> > 
> > Is there a function in R which replaces the NAs with "interpolated"
> > values between -86 and -96?
> 
> maybe something like 
> 
> > x <- c(1,2,NA, NA, NA, 10)
> > indx <- which(is.na(x))
> > x[is.na(x)] <- mean(c(x[indx[1]-1], x[indx[length(indx)]+1]))
> > x
> [1]  1  2  6  6  6 10
> 
> where `mean' is to be replaced with your interpolation :-)
> 
> Torsten

How about this:

y <- c(1, 2, NA, NA, NA, 10)
x <- seq(along=y)
approx(x,y,x)$y
#[1]  1  2  4  6  8 10

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list