[R-sig-Geo] How to replace coordinates of Polygons

Ben Mazzotta benjamin.mazzotta at tufts.edu
Mon Jul 19 16:21:00 CEST 2010


Dear R geographers:

I'm able to replace the coordinates of any given polygon, but not 
construct apply() family commands or for() loops to accomplish the same 
task. How can I construct a simple loop or apply() command that will 
sequentially replace all of the coordinates in a SpatialPolygons object?

As far as I understand, the coordinates of a polygon are kept in a slot 
referred as follows:
map at polygons[[x]]@Polygons[[y]]@coords

Using which, I can create mapply(foo, indexp, indexP) commands to 
extract the original coordinates and transform them.

# Define a pair of vectors indexp, indexP that together index every 
Polyon in the SpatialPolygons object map.
# Then extract coordinates as follows:
coords <- function(x,y) {map at polygons[[indexp]]@Polygons[[indexP]]@coords}
# Or operate a function foo on the old coordinates
coords.alt <- mapply(foo, 
map at polygons[[indexp]]@Polygons[[indexP]]@coords[,1], 
map at polygons[[indexp]]@Polygons[[indexP]]@coords[,2])

So I can create lists and matrices of coordinates, and transform the 
coordinates.

It is possible to write a command that replaces coordinates using 
integers; but these commands fail when I attempt to use mapply() to 
replace existing coordinates. For example,

p at polygons[[1]]@Polygons[[1]]@coords <- foo(1,1)

will work fine, but the following will not.

newcoords <- function(indp, indP) {
     p at polygons[[indp]]@Polygons[[indP]]@coords <- foo(indp, indP)
     }
mapply(newcoords, indexp, indexP)


Have I missed something in the manual on coordinates that would enable 
me to transform the coordinates of all the Polygons in a 
SpatialPolygonsDataFrame according to some regular function of the old 
coordinates (x,y)? Is the only alternative to build a new 
SpatialPolygons data frame from scratch, beginning with the new coordinates?

If it would be useful, I can provide sample code that works on wrld_simpl.

Please advise. Thank you!


-- 
Ben Mazzotta, PhD Candidate
The Fletcher School, Tufts University
benjamin.mazzotta at tufts.edu



More information about the R-sig-Geo mailing list