由于某些原因,我无法使用@RichPauloo提供的解决方案,也无法获得一些帮助。
我有一个名为“ spdf”的SpatialPolygonsDataFrame(在下面的Dropbox链接中) https://www.dropbox.com/s/ibhp5mqbgfmmntz/spdf.Rda?dl=0
我使用了下面文章中的代码来获取边界内的网格数据。
Create Grid in R for kriging in gstat
library(sp)
grd <- makegrid(spdf, n = 10000)
colnames(grd) <- c('x','y');
outline <- spdf@polygons[[1]]@Polygons[[1]]@coords
library(splancs)
new_grd <- grd[inout(grd,outline), ]
这就是我得到的:
黑点是makegrid的“ grd”
蓝点以“轮廓”为边界
红点是“ new-grd”,作为边界内的网格
如您所见,它没有捕获边界内的所有数据?我究竟做错了什么?
答案 0 :(得分:0)
尝试一下:
# packages
library(sp)
# make grid
grd <- makegrid(spdf, n = 100)
colnames(grd) <- c('x','y') # assign names to columns
# check the class
class(grd)
# transform into spatial points
grd_pts <- SpatialPoints(coords = grd,
proj4string=CRS(as.character(NA)))
# check the class again
class(grd_pts)
# show that points fall outside of polygon
plot(spdf)
points(grd_pts)
# subset for points within the polygon
grd_pts_in <- grd_pts[spdf, ]
# visualize
plot(spdf)
points(grd_pts_in)
# transform grd_pts_in back into a matrix and data frame
gm <- coordinates(grd_pts_in) # matrix
gdf <- as.data.frame(coordinates(grd_pts_in)) # data frame