I am using R's various spatial analysis features. I have data from a number of sampling locations throughout Africa, distributed unevenly. For several reasons, it is of interest to break our Africa map down into grids and compare characteristics of grids, matched on several characteristics. Ultimately, we want to be able to randomly sample grids. However, due to the uneven distribution of sampling locations, having evenly sized grid cells is problematic, because we would end up with some grids that have only one data point and other grids that have hundreds.
Basically, I know how to generate grid cells that are equal in area, with varying numbers of sampling locations ... however, what I want is essentially the opposite. Grid cells that vary in AREA, but with equal (or, realistically, near-equal, within a certain range) numbers of sampling locations. I recognize, too, that the solution may very likely involve polygons, rather than rectangular grid cells, but I am not sure how to implement this.
Simplified, reproducible example below, which takes a shapefile of Africa, randomly generates locations across Africa (ignoring for now that many of these are randomly generated in the ocean), and layers an even grid across it:
library(maptools)
library(lattice)
# Import shapefile of Africa
data(wrld_simpl, package="maptools")
africa <- wrld_simpl[wrld_simpl$REGION==2,]
# Randomly generate 200 coordinates
locations <- cbind.data.frame( x = runif(200, min(coordinates(africa)[,1]), max(coordinates(africa)[,1])),
y = runif(200, min(coordinates(africa)[,2]), max(coordinates(africa)[,2])))
coordinates(locations) <- ~ x + y
proj4string(locations) <- proj4string(africa)
# Verify with plot
plot(africa)
points(locations, pch=16, bg="black")
# Create spatial grid
bb <- bbox(africa)
cs <- c(10, 10) # cell size
cc <- bb[, 1] + (cs/2) # cell offset
cd <- ceiling(diff(t(bb))/cs) # number of cells per direction
grd <- GridTopology(cellcentre.offset=cc, cellsize=cs, cells.dim=cd)
sp_grd <- SpatialGridDataFrame(grd,
data=data.frame(id=1:prod(cd)),
proj4string=CRS(proj4string(africa)))
# Plot grid with randomly generated coordinates
spplot(sp_grd, "id", colorkey=FALSE,
panel = function(..., col.regions) {
panel.gridplot(..., border="black",col.regions="white")
sp.polygons(africa)
sp.points(locations, cex=1.2, pch=16, col="black")
panel.text(...,col="red")
})
# Can use 'over' funciton to find grid cells associated with each of our random points
# over(locations,sp_grd)
So, I know how to overlay this grid, count the number of sampling locations in each cell, extract data values for each cell, etc. etc. However, I am not sure how to proceed from here.
How would I generate grid cells (or polygons) that encompass the extent of my map area of interest, whereby the geographical area of the cells (or polygons) is variable but the number of sampling locations within each is fixed (or within a certain range)?
I am very new to the spatial analysis world.