[R] how to do interpolation

Jim Lemon jim at bitwrit.com.au
Tue Sep 4 12:54:44 CEST 2007


Yogesh Tiwari wrote:
> Hello R Users,
> 
> How to make a variable equidistance with time i.e. how to interpolate a
> variable if it is not sampled at equal time interval.
> 
Hi Yogesh,
Don't know whether this will suit your purpose. I wrote it to enable 
color-coded plotting of highly variable data. If you pass your intervals 
as "yvec", it will linearly interpolate values of "xvec" so that the 
maximum difference between "yvec"s is "maxjump". If the "yvec"s are not
multiples of "maxjump", you will get some smaller intervals.

linterp<-function(xvec,yvec,interp=NA,maxjump=1) {
  if(is.list(xvec) && missing(yvec)) {
   yvec<-xvec$y
   xvec<-xvec$x
  }
  if(!missing(xvec) && !missing(yvec)) {
   newlength<-oldlength<-length(xvec)
   oldrows<-1:oldlength
   for(l in 2:oldlength) {
    # use the y values as a default
    if(is.na(interp[1])) ninserts<-ceiling(abs(yvec[l]-yvec[l-1])/maxjump)
    # assume interp is already a function of the successive x/y pairs
    else ninserts<-ceiling(abs(interp[l-1])/maxjump)
    oldrows[l]<-oldrows[l-1]+ninserts
    newlength<-newlength+ninserts-1
   }
   xy<-list(x=rep(NA,newlength),y=rep(NA,newlength))
   xy$x[oldrows]<-xvec
   # if xvec and yvec are not the same length, give up
   if(oldlength == length(yvec)) {
    xy$y[oldrows]<-yvec
    for(index in 1:(oldlength-1)) {
     ninterp<-oldrows[index+1]-oldrows[index]
     if(ninterp > 1) {
      xinc<-(xvec[index+1]-xvec[index])/ninterp
      yinc<-(yvec[index+1]-yvec[index])/ninterp
      for(istep in 1:(ninterp-1)) {
       xy$x[oldrows[index]+istep]<-xy$x[oldrows[index]+istep-1]+xinc
       xy$y[oldrows[index]+istep]<-xy$y[oldrows[index]+istep-1]+yinc
      }
     }
    }
    return(xy)
   }
   else cat("xvec and yvec must have the same length!\n")
  }
  cat("Usage: linterp(xvec,yvec,interp=NA,maxjump=1)\n")
}


Jim



More information about the R-help mailing list