Skip to contents

Performs linear interpolation using approx() with linear extrapolation beyond the data range. This function is particularly useful when you need to estimate values outside the range of your observed data points.

Usage

approxExtrap(
  x,
  y,
  xout,
  method = "linear",
  n = 50,
  rule = 2,
  f = 0,
  ties = "ordered",
  na.rm = FALSE
)

Arguments

x

Either a vector of x-coordinates of points to be interpolated, or a list with components x and y. If a list is provided, the y parameter is ignored.

y

Vector of y-coordinates of points to be interpolated, corresponding to x.

xout

Vector of points at which to evaluate the interpolation/extrapolation.

method

Specifies the interpolation method. Only "linear" is currently supported. The default is "linear".

n

If xout is not specified, interpolation is done at n equally spaced points covering the range of x. The default is 50.

rule

An integer (1 or 2) describing how interpolation is to take place outside the interval min(x), max(x). See approx() for details. The default is 2.

f

For method = "constant", a number between 0 and 1 inclusive, indicating how interpolation should behave at jump discontinuities. See approx() for details. The default is 0.

ties

Handling of tied x values. See approx() for details. The default is "ordered".

na.rm

Logical indicating whether NA values should be removed before interpolation. The default is FALSE.

Value

A list with components:

x

The x-coordinates where interpolation was performed (same as input xout)

y

The interpolated/extrapolated y-values corresponding to xout

Details

The function first performs standard linear interpolation using approx(). For points outside the range of the input data, it performs linear extrapolation using the slope defined by the first two points (for low extrapolation) or last two points (for high extrapolation).

The function handles duplicate x-values by removing them and orders the data by x-values to ensure proper interpolation and extrapolation.

See also

approx for the base interpolation function.

Examples

# Basic interpolation and extrapolation
x <- 1:5
y <- c(2, 4, 3, 6, 5)
approxExtrap(x, y, xout = c(0, 1, 3.5, 5, 6))
#> $x
#> [1] 0.0 1.0 3.5 5.0 6.0
#> 
#> $y
#> [1] 0.0 2.0 4.5 5.0 4.0
#> 

# With NA values (when na.rm = TRUE)
x <- c(1, 2, NA, 4, 5)
y <- c(2, 4, 5, 6, 5)
approxExtrap(x, y, xout = 1:6, na.rm = TRUE)
#> $x
#> [1] 1 2 3 4 5 6
#> 
#> $y
#> [1] 2 4 5 6 5 4
#>