I have a number of points and would like to assign an ID based on the grid cell they intersect with. I know using the sf
package you could use st_intersections
or st_intersects
to do this. However, for large datasets with millions of features/points this can take a long time (or just cause R to crash).
Having a grid system on a projected CRS (British National Grid in my example) means there is a consistent shape and the coordinates (xmin, ymin, xmax and ymax) will always provide the full extent for every cell. Is there a non-spatial method using something in tidyverse
or data.table
for example that can take advantage of this to assign grid IDs.
Here is my sample data (and if anyone can show me a cleaner way of extracting the xmin, ymin, xmax and ymax for each grid cell that would be appreciated as well):
library(sf)
library(dplyr)
BBox <- st_bbox(c(xmin = 0, xmax = 10000, ymax = 10000, ymin = 0), crs = st_crs(27700))
Grid <- st_as_sfc(BBox) %>%
st_make_grid(square = TRUE, cellsize = c(1e3, 1e3)) %>%
cbind(data.frame(ID = sprintf(paste("GID%0",nchar(length(.)),"d",sep=""), 1:length(.)))) %>%
st_sf()
Points <- st_sample(st_as_sfc(BBox), 3000, exact = TRUE) %>%
st_sf('ID' = seq(length(.)), 'geometry' = .) %>%
mutate(X = st_coordinates(.)[,1],
Y = st_coordinates(.)[,2])
Table <- NULL
for(i in 1:nrow(Grid)) {
Row <- cbind(as.numeric(st_bbox(Grid[i,])[1]),
as.numeric(st_bbox(Grid[i,])[2]),
as.numeric(st_bbox(Grid[i,])[3]),
as.numeric(st_bbox(Grid[i,])[4]))
Table <- as.data.frame(rbind(Table, Row))
}
names(Table) <- c("xmin","ymin","xmax","ymax")
Grid <- cbind(Grid,Table)