r - 在 R 中的空间数据框中查找最近的网格值

标签 r geospatial raster gstat

我正在学习空间数据帧。我创建了一个简单的示例,它使用反距离加权 (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 of points and IDW values

最佳答案

您可以将xy转换为SpatialPoints:SpatialPoints(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")

enter image description here

关于r - 在 R 中的空间数据框中查找最近的网格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30096740/

相关文章:

javascript - 在 Photoshop 或 R 中将来自耦合显微镜/光谱学的图像和数据拼接成全景图

r - & 和 &&, | 有什么区别和 ||在 R 中?

r - ggplot : manual color assignment for single variable only

R测量距海岸线的距离

javascript - Mapbox.js : set map bounds on an area on both side of the date-line

r - 在大型栅格时间序列中使用 moveFun 的最有效方法是什么?

r - 如何调整使用 R 和 ggplot2 创建的箱线图中的框的大小以考虑不同箱线图中的不同频率?

r - 扩展 R 中的内存大小限制

java - 如何计算地理点和给定多边形之间的距离(以米为单位)?

r - 绘制栅格时将 par() 设置更改为默认值