Skip to content

Instantly share code, notes, and snippets.

@samclifford
Created March 1, 2017 01:39
Show Gist options
  • Select an option

  • Save samclifford/7c7f0d98046fa7ea504f3bedcece0afe to your computer and use it in GitHub Desktop.

Select an option

Save samclifford/7c7f0d98046fa7ea504f3bedcece0afe to your computer and use it in GitHub Desktop.
A function for snapping points to a grid. The grid doesn't even have to be regular!
library(raster)
library(tidyverse)
get.nearest.neighbour <- function(point_x,
point_y,
grid){
dists <- pointDistance(
matrix(c(point_x,point_y), nrow = 1),
as.matrix(grid[, c('longitude','latitude')]),
lonlat = F)
idx <- which.min(dists)
return(idx)
}
# make points
my.points <- data.frame(x=runif(n=100),
y=runif(n=100))
# make a grid
my.grid <- expand.grid(longitude=seq(0, 1, by=0.1),
latitude=seq(0, 1, by=0.1)) %>%
mutate(idx=1:nrow(.))
# find nearest
my.points %<>%
rowwise %>%
mutate(idx = get.nearest.neighbour(x, y, my.grid)) %>%
ungroup %>%
inner_join(my.grid)
head(my.points)
# visualise
ggplot(data=my.grid, aes(x=longitude,
y=latitude)) +
theme_void() +
geom_tile(fill=NA, color="grey90") +
geom_text(aes(label=idx), color="grey90") +
geom_text(data=my.points,
aes(label=idx, x=x, y=y)) +
coord_equal()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment