问题
I have a grid of (x, y, z) values and I want a function that can approximate z-values when it is given (x,y) points that lie beyond the grid.
I have tried to solve the question using the Akima package (code block 3), but I can't seem to get the interp function to work with the linear=FALSE option that is required to extrapolate beyond the grid.
Data:
# Grid data
x <- seq(0,1,length.out=6)
y <- seq(0,1,length.out=6)
z <- outer(x,y,function(x,y){sqrt(x^2+y^3)})
Visualize data (not essential for question):
## Visualize the data - Not important for question ##
jet.colors <- colorRampPalette( c("Royal Blue", "Lime Green") )
nbcol <- 100
color <- jet.colors(nbcol)
nrz <- nrow(z)
ncz <- ncol(z)
zfacet <- z[-1, -1] + z[-1, -ncz] + z[-nrz, -1] + z[-nrz, -ncz]
facetcol <- cut(zfacet, nbcol)
pmat <- persp(x, y, z, d = 1,r = 4,
ticktype="detailed",
col = color[facetcol],
main = "Title",
xlab="x value",
ylab = "y value",
zlab= "z value",
scale=FALSE,
expand=0.6,
theta=-40,
phi=25)
## End visualization ##
My attempt at solving the question using Akima package
library(akima)
# Vectorize the grid:
zz <- as.vector(z)
# create all combinations of x and y
xy <- expand.grid(x,y)
# What we want:
sqrt(0.7^2 + 0.7^3) # c(0.7, 0.7) = 0.9126883
sqrt(0.7^2 + 1.2^3) # c(0.7, 1.2) = 1.489295
# We get a result for the first point inside the grid,
# but not for the second one outside the grid.
# This is expected behaviour when linear=TRUE:
interp(xy[,1], xy[,2], zz, xo = c(0.7), yo= c(0.7, 1.2), linear=TRUE)
# = (0.929506, NA)
# When LINEAR = FALSE we get z= 0, 0!!
interp(xy[,1], xy[,2], zz, xo = c(0.7), yo= c(0.7, 1.2), linear=FALSE, extrap = TRUE)
# = (0, 0)
# Dropping extrap=TRUE we see that both are actually NA in this case
interp(xy[,1], xy[,2], zz, xo = c(0.7), yo= c(0.7, 1.2), linear=FALSE)
# = (NA, NA)
# What is going on?
Using R 3.1.3 and akima_0.5-11.
回答1:
Got a result by using interp.old() directly:
interp.old(xy[,1], xy[,2], zz, xo = c(0.7), yo= c(0.7, 1.2), ncp=2, extrap=TRUE)
# = (0.9211469, 1.472434)
I am not sure if this is a bug in the interp() function. interp() is a wrapper that calls interp.old() if linear=TRUE and interp.new() if linear=FALSE. The interp.new() function seems to fail.
Note that the use of the ncp parameter is deprecated. From the manual:
ncp - deprecated, use parameter linear. Now only used by interp.old(). meaning was: number of additional points to be used in computing partial derivatives at each data point. ncp must be either 0 (partial derivatives are not used), or at least 2 but smaller than the number of data points (and smaller than 25)
来源:https://stackoverflow.com/questions/29364470/extrapolation-beyond-a-grid-of-data