group data into squares
On Wed, 29 Nov 2006, Luis Ridao Cruz wrote:
R-sig-geo-help, I have locations of fish abundance which I want to aggregate into squares. The code below creates the grid: library(sp) test <- GridTopology(c(-10.5,60),c(0.1,0.1),c(67,35)) coordinates(test) coordinatevalues(test) yy <-SpatialGrid(grid=test) plot(yy,pch=16,cex=0.3,col=1) and within each cell the total abundance of fish should be specified. How can I do this?
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
Thanks in advance
version
_ platform i386-pc-mingw32 arch i386 os mingw32 system i386, mingw32 status major 2 minor 4.0 year 2006 month 10 day 03 svn rev 39566 language R version.string R version 2.4.0 (2006-10-03)
_______________________________________________ R-sig-Geo mailing list R-sig-Geo at stat.math.ethz.ch https://stat.ethz.ch/mailman/listinfo/r-sig-geo
Roger Bivand Economic Geography Section, Department of Economics, Norwegian School of Economics and Business Administration, Helleveien 30, N-5045 Bergen, Norway. voice: +47 55 95 93 55; fax +47 55 95 95 43 e-mail: Roger.Bivand at nhh.no