# [R-sig-Geo] group data into squares

Michael Sumner mdsumner at utas.edu.au
Wed Nov 29 22:51:26 CET 2006

```Here is a variant on Denis' method that scales up for large numbers of
points. You have to be sure no points fall outside your grid, or
tabulate will be in error:

# set up grid
nx <- 67
ny <- 35
test <- matrix (0, nrow=ny, ncol=nx)
xmin <- -10.5
ymin <- 60
xinc <- 0.1
yinc <- 0.1

# generate random sample points
npts <- 5000
pts <- cbind (x = runif (npts) * nx * xinc + xmin,
y = runif (npts) * ny * yinc + ymin)

# count points in grid (you should check none fall out of bounds)
cps <- ceiling(cbind((pts[,1] - xmin)/xinc, (pts[,2] - ymin)/yinc))
tps <- tabulate((cps[, 1] - 1) * ny + cps[, 2], nx * ny)
t2 <- matrix(tps, ny, nx)
table(t2)

## try again to show result in terms of corners of cell coordinates
xx <- seq(xmin, by = xinc, length = nx+1)
yy <- seq(ymin, by = yinc, length = ny+1)

npts <- 50
pts <- cbind (x = runif (npts) * nx * xinc + xmin,
y = runif (npts) * ny * yinc + ymin)

# count points in grid

cps <- ceiling(cbind((pts[,1] - xmin)/xinc, (pts[,2] - ymin)/yinc))
tps <- tabulate((cps[, 1] - 1) * ny + cps[, 2], nx * ny)
t2 <- matrix(tps, ny, nx)points(pts)

image(xx, yy, t(t2))

```