Home > Software engineering >  Finding z value for given x,y pair in by interp() returned list (rlang)
Finding z value for given x,y pair in by interp() returned list (rlang)

Time:06-14

I am using in R the akima interp() function to smooth GPS coordinates regarding the measured altitude.

s = interp(x, y, z, nx=100, ny=100)
  • X are longitude values
  • Y are latitude values
  • Z the corresponding altitude

I want a corresponding Z value to a given X,Y pair by using the returned list s.smooth.

How it must be implemented?

Actually, I am only able to use

df1<-data.frame(s.smooth)
df1[which.min(abs(x1-df1$x))]

to get the nearest x value for one value x1.

I need a function like z_i=f(x_i,y_i) with given x_i and y_i. This position pare is not part of the initial lists x,y,z.

CodePudding user response:

To get the interpolated value at specific values of x and y, you can use the xo and yo arguments of interp. To vectorize this and return the results in a data frame, you can write a little wrapper function:

library(akima)

interp_at <- function(x, y, z, xout, yout) {
  do.call(rbind, lapply(seq_along(xout), function(i) {
    as.data.frame(t(unlist(interp(x, y, z, xo = xout[i], yo = yout[i]))))
  }))
}

So, if we had the following data:

set.seed(1)
x <- rnorm(500)
y <- rnorm(500)
z <- 10 - x^2 - y^2

and we want to know the value at [0, 0], [1, 0.5], and [2, 1] we can just do:

interp_at(x, y, z, xout = c(0, 1, 2), yout = c(0, 0.5, 1))
#>   x   y        z
#> 1 0 0.0 9.992207
#> 2 1 0.5 8.727516
#> 3 2 1.0 4.982223

Created on 2022-06-13 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related