rlistinterpolation

Interpolating Values from Lists in R Using approx() in R


I'm trying to interpolate values contained in lists, but the approx() function doesn't seem to work with them. I've also tried using apply() functions without success.

Could someone suggest an easy way to interpolate using lists?

Here is my code:

r
Copy code
x <- list(c(20, 25), c(24, 25))
y <- list(c(0.98, 0.96), c(0.94, 0.96))
xout <- c(23.1, 24, 1)

approx(x, y, xout)

Solution

  • Map is your friend.

    > Map(approx, x, y, list(xout))
    [[1]]
    [[1]]$x
    [1] 23.1 24.0 31.0
    
    [[1]]$y
    [1] 0.9676 0.9640     NA
    
    
    [[2]]
    [[2]]$x
    [1] 23.1 24.0 31.0
    
    [[2]]$y
    [1]   NA 0.94   NA
    

    The NA are due to the fact that xout is not contained in x, i.e. approx only interpolates but doesn't extrapolate.


    Data:

    x <- list(c(20, 25), c(24, 25))
    y <- list(c(0.98, 0.96), c(0.94, 0.96))
    xout <- c(23.1, 24, 31)  ## assuming c(23.1, 24, 1) was a typo