13

I have two points (5,0.45) & (6,0.50) and need to find the value when x=5.019802 by linear interpolation

But how to code it in R?

I tried the code below but just got a graph.

x <- c(5,6)
y <- c(0.45,0.50)

interp <- approx(x,y)

plot(x,y,pch=16,cex=2)
points(interp,col='red')
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
Ys Kee
  • 145
  • 1
  • 5
  • The exact value 5.019802, does not appear in `interp$x`. You could try to find the closest point to the target value with , `targetVal = 5.019802 ; which.min(abs(interp$x - targetVal ))` give index as 2, `interp$x[2],interp$y[2]` would be closest point to desired value – Silence Dogood Oct 18 '16 at 23:19

2 Answers2

22

You just need to specify an xout value.

approx(x,y,xout=5.019802)
$x
[1] 5.019802

$y
[1] 0.4509901
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
4

I suggest make a function that solves for y = mx + b.

x = c(5,6)
y = c(0.45, 0.50)
m <- (y[2] - y[1]) / (x[2] - x[1]) # slope formula
b <- y[1]-(m*x[1]) # solve for b
m*(5.019802) + b

# same answer as the approx function
[1] 0.4509901
Matt L.
  • 397
  • 4
  • 12