Skip to content
Prev 1524 / 29559 Next

group data into squares

On Wed, 29 Nov 2006, Luis Ridao Cruz wrote:

            
Use the overlay() method. Something like:

fish <- SpatialPoints(cbind(runif(10000, bbox(yy)[1,1], bbox(yy)[1,2]), 
  runif(10000, bbox(yy)[2,1], bbox(yy)[2,2])))
plot(fish, add=TRUE, pch=".", col="green")
out <- overlay(yy, fish)
out1 <- formatC(out, width=4, format="d", flag="0")
# otherwise it sorts 1, 10, 100, ...
res <- aggregate(rep(1, length(out)), list(out1), sum)

and res$x are the counts. Because some cells have zero counts, they are 
not in res$Group.1, so maybe:

res1 <- numeric(nrow(coordinates(yy)))
res1[as.integer(as.character(res$Group.1))] <- res$x
# to insert the values in the cells with positive counts
table(res1)

where the zero counts are now in place. I didn't check whether the counts 
had ended up in the correct cells here - too many, but:

test <- GridTopology(c(-10.5,60),c(1,1),c(7,4))
yy <-SpatialGrid(grid=test)
fish <- SpatialPoints(cbind(runif(10, bbox(yy)[1,1], bbox(yy)[1,2]),
  runif(10, bbox(yy)[2,1], bbox(yy)[2,2])))
out <- overlay(yy, fish)
out1 <- formatC(out, width=4, format="d", flag="0")
res <- aggregate(rep(1, length(out)), list(out1), sum)
res1 <- numeric(nrow(coordinates(yy)))
res1[as.integer(as.character(res$Group.1))] <- res$x
yyy<- SpatialGridDataFrame(grid=test, data=data.frame(fish_count=res1))
image(yyy)
text(coordinates(yyy), labels=yyy$fish_count)
plot(fish, add=TRUE, pch=16, col="blue", cex=0.6)

looks OK.

Roger