Search code examples
rclip

Selection and extraction of points (shapefile) within a polygon in R


I have two shape-files; one is a point file (some information for world) and the other is a 21-countries shape-file.

I need to extract the points which falls with in a country. I have to repeat this step in 21 times in QGIS or ArcGIS.

Is there any way to do this in R and if is in batch processing, that would be really great as I have to repeat this for other 4 data sets as well. Thanks in advance


Solution

  • So as an example how to use over() consider the following simulated data.

    library(raster)
    library(sp)
    
    #generate point distribution | with (x,y) coordinates
    set.seed(42);pts <- SpatialPoints(data.frame(x = runif(30, 1, 5), y = runif(30, 1, 5)))
    
    #create polygons
    df<-data.frame(X = c(rep(1,5),rep(2,5),rep(3,5),rep(4,5),rep(5,5)),
                   Y = c(rep(seq(1,5,1),5)))
    df$cell<-1:nrow(df) #polygon identifier (for later)
    
    #make into spatial object (probably better way to do this)
    coordinates(df) <- ~X+Y 
    rast <- raster(extent(df), ncol = 5, nrow = 5)
    grid<-rasterize(df, rast, df$cell, FUN = max)
    grid<-rasterToPolygons(grid) #create polygons
    
    #plot to check
    plot(grid); points(pts)
    
    #and extract
    pointsinpolygon = over(SpatialPolygons(grid@polygons), SpatialPoints(pts))
    

    The last bit you can also do as

    df$pointsinpolygon <- over(SpatialPolygons(grid@polygons), SpatialPoints(pts))

    to write the results directly to the dataframe.