Skip to content

Instantly share code, notes, and snippets.

@famuvie
Last active December 30, 2015 01:59
Show Gist options
  • Save famuvie/7759374 to your computer and use it in GitHub Desktop.
Save famuvie/7759374 to your computer and use it in GitHub Desktop.
Counting the number of points in each cell of a regular grid
library(ggplot2)
# Some fake points
N <- 500
loc <- matrix(runif(2*N), ncol=2)
# A regular (not necessarily square) grid
n.row <- 10
n.col <- 10
xrange <- range(loc[,1])
yrange <- range(loc[,2])
breaks.x <- seq(xrange[1]-.01*diff(xrange), xrange[2]+.01*diff(xrange), length.out = n.col + 1)
breaks.y <- seq(yrange[1]-.01*diff(yrange), yrange[2]+.01*diff(yrange), length.out = n.row + 1)
# Visualize
qplot(loc[,1], loc[,2]) + geom_hline(aes(yintercept=y), data=data.frame(y=breaks.y), col='gray') + geom_vline(aes(xintercept=x), data=data.frame(x=breaks.x), col='gray') + theme_bw()
# Count
# cut(x, breaks) codes the values in x according to which interval they fall. See ?cut.
grid.x <- as.numeric(cut(loc[,1], breaks.x))
grid.y <- as.numeric(cut(loc[,2], breaks.y))
# grid.codes have, for each data point, the cell it belongs to
grid.codes <- data.frame(grid.x, grid.y)
# see head(grid.codes)
# tabulate counts
table(grid.codes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment