Search code examples
rsampler-raster

How to select one point per raster grid cell?


I have a point shapefile ("search_effort.shp") that is highly clustered and an NDVI raster (resolution in m: 30.94948, 30.77829). I would like to subset my search_effort.shp by selecting 1 point per raster grid cell and create a new search_effort shapefile. I am using R version 4.0.3

I think I could have used Package ‘gridsample’ (in 'raster' v1.3-1), but it was removed from the CRAN repository and I would prefer not to use the archived version. Is there another way to do this in R?

I have also tried sample.grid but I do not know how to specify my raster as the grid, and have tried the following:

# NDVI raster to be used as the reference extent
NDVI_extent <-readGDAL('C:/Model_layers/NDVI.tif')

# Load the file names  
layername <- "SearchEffort"

# Read in the shapefile
search_effort <- readOGR(dsn= ".", layer = layername)
plot(search_effort)

# Set the reference extent
r <- raster(NDVI_extent)

# Extract coordinates from the shapefile
search_effort@coords <- search_effort@coords[, 1:2]

#Subset points
sample.grid(search_effort, cell.size = c(30.94948, 30.77829), n = 1)

I get the following error: "Error in validObject(.Object) : invalid class “GridTopology” object: cellsize has incorrect dimension." I get the same error regardless of the cell.size I specify.


Solution

  • Example data

    library(raster)
    r <- raster(res=30)
    values(r) <- 1:ncell(r)
    x <- runif(1000,-180,180)
    y <- runif(1000,-90,90)
    xy <- cbind(x, y)
    

    Solution

    library(dismo)
    s <- gridSample(xy, r, n=1) 
    

    Illustration

    plot(as(r, "SpatialPolygons"))
    points(s, col="red")
    points(xy, cex=.1, col="blue")