Search code examples
rgeospatialinout

Grid points within polygon: previous solution does not work for me


For some reason I can't get the solution provided by @RichPauloo to work and do appreciate some help.

I have a SpatialPolygonsDataFrame called "spdf" (in the dropbox link below) https://www.dropbox.com/s/ibhp5mqbgfmmntz/spdf.Rda?dl=0

I used the code from below post to get the grid data within the boundary.

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), ]

Here is what I get:

Here is the plot of grids

  • Black dots are "grd" from makegrid

  • Blue dots are "outline" as boundary

  • Red dots are"new-grd" as the grid within the boundary

As you can see it does not capture all the data within the boundary? What am I doing wrong?


Solution

  • Try this:

    # 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