Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seeking 2D version of approxfun()

I am seeking in R a 2D version of stats::approxfun() that can generate an interpolation function f(x,y) from an (x,y,z) dataset. I have not found one in the package akima or elsewhere.

like image 504
Ronnen Levinson Avatar asked Jan 18 '16 05:01

Ronnen Levinson


1 Answers

I would try to readapt the interp.surface function from the R package fields. An example readapted from the ?interp.surface:

Load package

library(fields)
#> Warning: package 'fields' was built under R version 4.1.2
#> Loading required package: spam
#> Warning: package 'spam' was built under R version 4.1.2
#> Loading required package: dotCall64
#> Warning: package 'dotCall64' was built under R version 4.1.2
#> Loading required package: grid
#> Spam version 2.7-0 (2021-06-25) is loaded.
#> Type 'help( Spam)' or 'demo( spam)' for a short introduction 
#> and overview of this package.
#> Help for individual functions is also obtained by adding the
#> suffix '.spam' to the function name, e.g. 'help( chol.spam)'.
#> 
#> Attaching package: 'spam'
#> The following objects are masked from 'package:base':
#> 
#>     backsolve, forwardsolve
#> Loading required package: viridis
#> Loading required package: viridisLite
#> 
#> Try help(fields) to get started.

Load data

data(lennon)
obj <- list(x = 1:20, y = 1:20, z = lennon[201:220, 201:220])

Define the approximating function

approxfun_2d <- function(x, y) {
  interp.surface(obj, cbind(x, y))
}

Test it

set.seed(1)
approxfun_2d(x = runif(1, min = 1, max = 20), y = runif(1, min = 1, max = 20))
#> [1] 33.34148

Plot original data

image.plot(obj)

Compute interpolations

x_interp <- runif(2e2, 1, 20)
y_interp <- runif(2e2, 1, 20)
z_interp <- approxfun_2d(x_interp, y_interp)

Plot approximation

quilt.plot(x_interp, y_interp, z_interp)

Created on 2021-11-23 by the reprex package (v2.0.1)

This is not 100% equal to a 2D version of approxfun, but it may be good enough for most purposes.

like image 167
agila Avatar answered Oct 29 '22 23:10

agila