When to Apply approxfun vs. approx in R (2 Examples)

This tutorial shows how to use the approx and approxfun interpolation functions in R.

Example Data

vec_a <- 1:3                            # Create example vectors
vec_a
# [1] 1 2 3
vec_b <- c(1, 2, 10)
vec_b
# [1]  1  2 10

Example 1: Linearly Interpolate Given Data Points Using approx() Function

approx_out <- approx(vec_a,             # Using approx() function
                     vec_b)
approx_out
# $x
#  [1] 1.000000 1.040816 1.081633 1.122449 1.163265 1.204082 1.244898 1.285714
#  [9] 1.326531 1.367347 1.408163 1.448980 1.489796 1.530612 1.571429 1.612245
# [17] 1.653061 1.693878 1.734694 1.775510 1.816327 1.857143 1.897959 1.938776
# [25] 1.979592 2.020408 2.061224 2.102041 2.142857 2.183673 2.224490 2.265306
# [33] 2.306122 2.346939 2.387755 2.428571 2.469388 2.510204 2.551020 2.591837
# [41] 2.632653 2.673469 2.714286 2.755102 2.795918 2.836735 2.877551 2.918367
# [49] 2.959184 3.000000
# 
# $y
#  [1]  1.000000  1.040816  1.081633  1.122449  1.163265  1.204082  1.244898
#  [8]  1.285714  1.326531  1.367347  1.408163  1.448980  1.489796  1.530612
# [15]  1.571429  1.612245  1.653061  1.693878  1.734694  1.775510  1.816327
# [22]  1.857143  1.897959  1.938776  1.979592  2.163265  2.489796  2.816327
# [29]  3.142857  3.469388  3.795918  4.122449  4.448980  4.775510  5.102041
# [36]  5.428571  5.755102  6.081633  6.408163  6.734694  7.061224  7.387755
# [43]  7.714286  8.040816  8.367347  8.693878  9.020408  9.346939  9.673469
# [50] 10.000000
plot(approx_out$x,                      # Create plot of approx output
     approx_out$y)

r graph figure 1 when apply approxfun vs approx

Example 2: Create Own Function for Interpolation Using approxfun()

manual_approxfun <- approxfun(vec_a,    # Using approxfun() function
                              vec_b)
plot(vec_a, vec_b)                      # Create plot of approxfun
curve(manual_approxfun,
      add = TRUE)

r graph figure 2 when apply approxfun vs approx

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top