[R] how to get points from SpatialPolygonsDataFrame

Roger Bivand Roger.Bivand at nhh.no
Mon Feb 4 14:22:53 CET 2008


Takatsugu Kobayashi <tkobayas <at> indiana.edu> writes:

> 
> try
> 
> tmp<- slot(ex_1.7.selected, 'polygons')
> sub.tmp <- slot(tmp[[1]],'Polygons')
> sub.tmp[[1]]@coords
> 
> will get you there.
> 
> taka
> 
> Jarek Jasiewicz wrote:
> > Milton Cezar Ribeiro wrote:
> >   
> >> Dear all,
> >>

> >>
> >> grd <- GridTopology(c(1,1), c(1,1), c(10,10))
> >> polys <- as.SpatialPolygons.GridTopology(grd)
> >> centroids <- coordinates(polys)
> >> x <- centroids[,1]
> >> y <- centroids[,2]
> >> z <- 1.4 + 0.1*x + 0.2*y + 0.002*x*x
> >> ex_1.7 <- SpatialPolygonsDataFrame(polys, data=data.frame(x=x, y=y, z=z,
> row.names=sapply(slot(polys, "polygons"), function(i) slot(i, "ID"))))
> >> ex_1.7.selected<-ex_1.7[1,]
> >> slot(ex_1.7.selected,"coords")

A recent thread on the (more relevant for your purposes) R-sig-geo list provides
code for doing at least part of what you say you want:

https://stat.ethz.ch/pipermail/r-sig-geo/2008-January/003075

Here, it would be:

library(sp)
grd <- GridTopology(c(1,1), c(1,1), c(10,10))
polys <- as.SpatialPolygons.GridTopology(grd)
centroids <- coordinates(polys)
x <- centroids[,1]
y <- centroids[,2]
z <- 1.4 + 0.1*x + 0.2*y + 0.002*x*x
ex_1.7 <- SpatialPolygonsDataFrame(polys, data=data.frame(x=x, y=y,
  z=z, row.names=sapply(slot(polys, "polygons"),
  function(i) slot(i, "ID"))))
pls <- slot(ex_1.7, "polygons")
# from construction, we know that each Polygons object in pls has five 2D
# coordinates and only one part, so we won't check:
res <- t(sapply(pls, function(x) c(slot(slot(x, "Polygons")[[1]], "coords"))))
# steps along the list of Polygons objects, pulling out the "coords" slot
# of the first and only Polygon object in its "Polygons" slot, finally
# flattening them from a matrix to a vector as you request, and transposing
str(res)
res[1,]

Hope this helps,

Roger



More information about the R-help mailing list