I'm trying to do bilinear interpolation from a grid to a set of irregular points, same as How can I get the value of a kernel density estimate at specific points?. However, when I try the accepted answer there I get a dimension mismatch error:
n <- 100
x <- rnorm(n)
y <- 3 + 2* x * rexp(n) + rnorm(n)
# add some outliers
y[sample(1:n,20)] <- rnorm(20,20,20)
DF <- data.frame(x,y)
# Calculate 2d density over a grid
library(MASS)
dens <- kde2d(x,y)
# create a new data frame of that 2d density grid
# (needs checking that I haven't stuffed up the order here of z?)
gr <- data.frame(with(dens, expand.grid(x,y)), as.vector(dens$z))
names(gr) <- c("x", "y", "z")
newdata=data.frame(xgr=x, ygr=y)
dens <- fields::interp.surface(gr, newdata)
# the interp.surface output is 2x as long as dim(newdata)[1]
length(dens)
dim(newdata)[1]
Any help appreciated, and apologies if this is trivial!