Search code examples
rinterpolation

Interpolate a single row of a table


I am trying to interpolate a row of a data frame at a single point. I can use approx to get a single value, but need to end up with a vector or single line with one value for each column of the data frame.

df <- data.frame(
  x = c(1.1, 1.2, 1.3, 1.4),
  y1 = c(-.6,-.4, .4, 1.2),
  y2 = c(-.7, -.4, .4, .46),
  y3 = c(-.8, -.3, .5, 1.2)
)
df
    x   y1    y2   y3
1 1.1 -0.6 -0.70 -0.8
2 1.2 -0.4 -0.40 -0.3
3 1.3  0.4  0.40  0.5
4 1.4  1.2  0.46  1.2

target_x <- 1.24

## Works
approx(df$x, df$y1, target_x)$y
>[1] -0.08

### looking for something like approx(df$x, df[,2:4], target_x)
## should return:
> [1] -0.08 -0.08  0.02

Linear interpolation is fine, I do not need to extrapolate beyond the existing table. Either base R or dplyr approaches are preferred.


Solution

  • You're looking for

    sapply(df[, 2:4], \(y) approx(x=df$x, y=y, xout=target_x)$y)
    #    y1    y2    y3 
    # -0.08 -0.08  0.02 
    

    Data:

    df <- structure(list(x = c(1.1, 1.2, 1.3, 1.4), y1 = c(-0.6, -0.4, 
    0.4, 1.2), y2 = c(-0.7, -0.4, 0.4, 0.46), y3 = c(-0.8, -0.3, 
    0.5, 1.2)), class = "data.frame", row.names = c(NA, -4L))
    
    target_x <- 1.24