[R-sig-Geo] converting grid objects to spatial polygon objects and export as shapefile

Roger Bivand Roger.Bivand at nhh.no
Thu Dec 10 10:11:53 CET 2009


On Wed, 9 Dec 2009, brwin338 at aol.com wrote:

>
> Good Evening:
> I have been trying to figure this one out but just can't make it work yet.
>
> Is there a straightforward way to convert a grid object (such as an 
> earthwide or regional long-lat grid) generated using sp into a spatial 
> polygon object that I could then export as a shapefile.  I want to be 
> able to use the maptools overlay function to assign locations to a grid 
> and then color each grid area based upon mean or other characteristics 
> of the locations within each grid.  I also want to create a shapefile 
> with attributes from each polygon saved in the @data component.  Please 
> excuse me if this is a simple problem or has been addressed previously 
> by the list but I have not been able to find an answer in previous 
> posts.

Have you considered coercing to SpatialPixels, then to 
SpatialPolygons: as(as(grd, "SpatialPixels"), "SpatialPolygons")?

gt <- GridTopology(c(-177.5, -87.5), c(5, 5), c(72, 36))
grd <- SpatialGrid(gt, proj4string=CRS("+proj=longlat"))
spix <- as(grd, "SpatialPixels")
spol <- as(spix, "SpatialPolygons")

Whether the sp package overlay methods will be more efficient on which 
representation is a question that needs addressing. Then something like:

pts <- spsample(grd, n=50000, type="random")
spts <- SpatialPointsDataFrame(pts, data=data.frame(x=rnorm(50000)))
o <- overlay(spol, spts)
spdf <- SpatialPolygonsDataFrame(spol, data=data.frame(id=row.names(spol),
   row.names=row.names(spol)))
spdf$xbar <- aggregate(spts$x, list(o), mean)$x
spplot(spdf, "xbar")

but you might just as well use the SpatialGrid* or SpatialPixels* 
representation, maybe?

Hope this helps,

Roger

>
> Joe
>
> 	[[alternative HTML version deleted]]
>
> _______________________________________________
> 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



More information about the R-sig-Geo mailing list