使用`fields :: interp.surface`从网格插入到不规则点

时间:2017-05-10 15:06:46

标签: r

我试图从网格到一组不规则点进行双线性插值,与How can I get the value of a kernel density estimate at specific points?相同。但是,当我尝试接受的答案时,我会收到尺寸不匹配错误:

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]

任何帮助表示赞赏,并且如果这是微不足道的话,请道歉!

1 个答案:

答案 0 :(得分:1)

无需创建gr对象。只需将dens直接传递给interp.surface

newdata=data.frame(x=x, y=y)
newdata$z <- fields::interp.surface(dens, newdata)