Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Approximate lookup in R

Tags:

lookup

r

I have the following lookup table:

lkp <- data.frame(
         x=c(0,0.2,0.65,0.658,1.3,1.76,2.7), 
         y=c(1,1,1,0.942,0.942, 0.92, 0.89)
       )

I would like to get the value of Y of a given X value.

If the X value exists in the table then the exact Y of the table should be returned. If the X value does not exist, then the Y value should be returned as linear interpolation of the 2 nearest neighbors (only the 2 nearest neighbors). I would not like to fit a model to the overall data.

for the above table

for X=0.2 Y=1 (exact lookup) 
for X=2 Y=0.91 (linear interpolation between the last 2 rows of the data frame)

Is there any ready function to do this?

like image 493
ECII Avatar asked Oct 09 '11 12:10

ECII


1 Answers

Yes, it's called approx.

> with(lkp, approx(x, y, xout=c(0.2, 2)))
$x
[1] 0.2 2.0

$y
[1] 1.0000000 0.9123404

See ?approx for more information.

like image 162
Andrie Avatar answered Sep 30 '22 15:09

Andrie