roberto feuda
roberto feuda

Reputation: 1

least square regression model

What is behind Approx and approxfun? I know that these two functions perform a linear interpolation, however I didn't find any reference on how they do that. I guess they use a least square regression model but I am not sure.

Finally, if it's true that they use a least square regression model what is the difference between them and lm + predict?

Upvotes: 0

Views: 238

Answers (1)

agstudy
agstudy

Reputation: 121608

As commented , you should read the source code. Interpolation problem

Find y(v), given (x,y)[i], i = 0,..,n-1 */

For example approxfun use a simple this algorithm for linear approximation :

  1. y(v), given (x,y)[i], i = 0,..,n-1 */
  2. find the correct interval (i,j) by bisection */
  3. Use i,j for linear interpolation

Here an R code that aprahrase the C function approx1 :

approx1 <- 
  function( v, x, y)
{
  ## Approximate  y(v),  given (x,y)[i], i = 0,..,n-1 */


  i <- 1
  j <- length(x) 
  ij <- 0

  ## find the correct interval by bisection */
    while(i < (j-1) ) { 
         ij <- floor((i + j)/2)
         if(v < x[ij]) 
             j <- ij 
         else 
           i <- ij
    }
  ## linear interpolation */

    if(v == x[j]) return(y[j])
    if(v == x[i]) return(y[i])

    return (y[i] + (y[j] - y[i]) * ((v - x[i])/(x[j] - x[i])))
  }

Upvotes: 1

Related Questions