Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use approxfun vs. approx

Tags:

r

The documentation for approxfun states that it is "often more useful than approx". I'm struggling to get my head around approxfun. When would approxfun be more useful than approx (and when would approx be more useful)?

like image 640
Drew Steen Avatar asked Oct 16 '12 21:10

Drew Steen


1 Answers

approx returns the value of the approximated function at (either) specified points or at a given number of points. approxfun returns a function which can then be evaluated at some specific points. If you need the approximation at points that you know at the time of making the approximation, approx will do that for you. If you need a function (in the mathematical sense) which will return the value of the approximation for some argument given later, approxfun is what you need.

Here are some examples.

dat <- data.frame(x=1:10, y=(1:10)^2)

The output from approx and approxfun using this data

> approx(dat$x, dat$y)
$x
 [1]  1.000000  1.183673  1.367347  1.551020  1.734694  1.918367  2.102041
 [8]  2.285714  2.469388  2.653061  2.836735  3.020408  3.204082  3.387755
[15]  3.571429  3.755102  3.938776  4.122449  4.306122  4.489796  4.673469
[22]  4.857143  5.040816  5.224490  5.408163  5.591837  5.775510  5.959184
[29]  6.142857  6.326531  6.510204  6.693878  6.877551  7.061224  7.244898
[36]  7.428571  7.612245  7.795918  7.979592  8.163265  8.346939  8.530612
[43]  8.714286  8.897959  9.081633  9.265306  9.448980  9.632653  9.816327
[50] 10.000000

$y
 [1]   1.000000   1.551020   2.102041   2.653061   3.204082   3.755102
 [7]   4.510204   5.428571   6.346939   7.265306   8.183673   9.142857
[13]  10.428571  11.714286  13.000000  14.285714  15.571429  17.102041
[19]  18.755102  20.408163  22.061224  23.714286  25.448980  27.469388
[25]  29.489796  31.510204  33.530612  35.551020  37.857143  40.244898
[31]  42.632653  45.020408  47.408163  49.918367  52.673469  55.428571
[37]  58.183673  60.938776  63.693878  66.775510  69.897959  73.020408
[43]  76.142857  79.265306  82.551020  86.040816  89.530612  93.020408
[49]  96.510204 100.000000

> approxfun(dat$x, dat$y)
function (v) 
.C(C_R_approxfun, as.double(x), as.double(y), as.integer(n), 
    xout = as.double(v), as.integer(length(v)), as.integer(method), 
    as.double(yleft), as.double(yright), as.double(f), NAOK = TRUE, 
    PACKAGE = "stats")$xout
<bytecode: 0x05244854>
<environment: 0x030632fc>

More examples of usage:

a <- approx(dat$x, dat$y)
af <- approxfun(dat$x, dat$y)

plot(dat)
points(a, pch=2)

enter image description here

plot(dat)
curve(af, add=TRUE)

enter image description here

or another example where a function is needed:

> uniroot(function(x) {af(x)-4}, interval=c(1,10))
$root
[1] 1.999994

$f.root
[1] -1.736297e-05

$iter
[1] 24

$estim.prec
[1] 6.103516e-05
like image 133
Brian Diggs Avatar answered Oct 12 '22 23:10

Brian Diggs