[R-sig-Geo] sum of point values within a grid square

Roger Bivand Roger.Bivand at nhh.no
Thu Apr 3 20:50:40 CEST 2008


On Thu, 3 Apr 2008, Andrew James Hoskins wrote:

> Hi all,
>
> I'm trying to get the sum of value z for all points that fall within a grid
> square.  I've been trying to use the overlay function on a grid converted to
> polygons, however, it returns the sum of the coordinates and the z values,
> how can I have it return only the sum of z?
> Also, once I have the sum of z how then can I assign that to it's
> corresponding grid square?
>
> ## Example code
>
> g <- GridTopology(c(-10,-10), c(1,1), c(21,21))
> g.poly <- as(g, "SpatialPolygons")
>
> x <- c(1:10,1:10)
> y <- c(10:1,10:1)
> z <- 1:20
>
> xyz <- SpatialPointsDataFrame(cbind(x,y),data.frame(z))
>
> ol <- overlay(xyz, g.poly, fn=sum)

This is quite a long way round. Something like:

SG <- SpatialGrid(g)
ol <- overlay(SG, xyz)
z_agg <- aggregate(xyz$z, list(ol=ol), sum)
names(z_agg)
n <- nrow(coordinates(SG))
df <- data.frame(z=rep(NA, n))
df$z[z_agg$ol] <- z_agg$x
SGDF <- SpatialGridDataFrame(g, data=df)
image(SGDF)

gets you there without having to create polygons, and aggregate() is a 
pretty flexible function. Check the ol vector for NAs, though.

Roger

>
>
> Thanks in advance.
>
> Andrew.
>
>
>
>

-- 
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




More information about the R-sig-Geo mailing list