[英]Finding nearest grid value in spatial dataframe in R
我正在學習空間數據框。 我創建了一個簡單的示例,該示例基於一組初始點,使用反距離權重(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))
#######
您可以將x
和y
轉換為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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.