2

我正在学习空间数据框。我创建了一个简单的示例,它使用反距离加权 (IDW) 根据一组初始点在网格中插入值。我现在想获得每个初始点的插值。我认为这应该相对容易,但很难找到一种优雅的方式。换句话说,我想在“geog2.idw”中为40个点(x,y)中的每一个找到最近的网格值。

代码

#adjusted from example created by Brian J. Knaus

#packages
library(gstat)
require(gstat)
require(lattice)
require(raster)
require(sp)

##### ##### ##### ##### #####
# Generate data.
set.seed(1)
x <- runif(40, -123, -110)
set.seed(2)
y <- runif(40, 40, 48)
set.seed(3)
z <- runif(40, 0, 1)

# Create spatial data.frame.
geog2 <- data.frame(x,y,z)

# Assigning coordinates results in spdataframe.
coordinates(geog2) = ~x+y


#create grid
pixels <- 100

geog.grd <- expand.grid(x=seq(floor(min(coordinates(geog2)[,1])),
                              ceiling(max(coordinates(geog2)[,1])),
                              length.out=pixels),
                        y=seq(floor(min(coordinates(geog2)[,2])),
                              ceiling(max(coordinates(geog2)[,2])),
                              length.out=pixels))
#
grd.pts <- SpatialPixels(SpatialPoints((geog.grd)))
grd <- as(grd.pts, "SpatialGrid")


##### ##### ##### ##### #####
# IDW interpolation.

geog2.idw <- idw(z ~ 1, geog2, grd, idp=6)

spplot(geog2.idw["var1.pred"])

##### ##### ##### ##### #####
# Image.

par(mar=c(2,2,1,1))
#
image(geog2.idw, xlim=c(-125, -110), ylim=c(40, 47))
#
contour(geog2.idw, add=T, lwd=0.5)
#
map("state", lwd=1, add=T)
map("county", lty=3, lwd=0.5, add=T)
#
points(x, y, pch=21, bg=c(1:4))

#######

Plot 点和 IDW 值

4

1 回答 1

3

您可以转为:并x使用以下功能:ySpatialPointsSpatialPoints(cbind(x,y))over

pts <- SpatialPoints(cbind(x, y))
pts.idw <- over(pts, geog2.idw["var1.pred"])

# Writing extracted values on the map:
image(geog2.idw, xlim=c(-125, -110), ylim=c(40, 47))
contour(geog2.idw, add=T, lwd=0.5)
map("state", lwd=1, add=T)
map("county", lty=3, lwd=0.5, add=T)
text(pts, round(pts.idw[,"var1.pred"],4), col = "blue")

在此处输入图像描述

于 2015-05-07T10:30:28.543 回答