extracting coordinates from polygon r

1.1k views Asked by At

I am trying to extract coordinates from numerous polygons, originally contained in a SpatialPolygons object:

 Sr1 = Polygon(cbind(c(2,4,4,1,2),c(2,3,5,4,2)))
 Sr2 = Polygon(cbind(c(5,4,2,5),c(2,3,2,2)))
 Srs1 = Polygons(list(Sr1), "s1")
 Srs2 = Polygons(list(Sr2), "s2")
 SpP = SpatialPolygons(list(Srs1,Srs2), 1:2)

I am trying to extract the coordinates from Sr1 and Sr2 from the SpP object. I saw this code elsewhere on stack exchange:

Coords<-SpP@polygons[[2]]@Polygons[[1]]@coords

I cannot understand the mismatch of the indexes in the square brackets, nevertheless it runs. But the output does not match the coordinates which I specified in Sr1 or Sr2. I have tried all the combinations of the indexes and cannot get the answer I am looking for!

1

There are 1 answers

2
hrbrmstr On BEST ANSWER

Are you sure? They look the same (only posting as an "answer" since it's too long for a comment):

library(sp)

Sr1 <- Polygon(cbind(c(2, 4, 4, 1, 2), c(2, 3, 5, 4, 2)))
Sr2 <- Polygon(cbind(c(5, 4, 2, 5), c(2, 3, 2, 2)))
Srs1 <- Polygons(list(Sr1), "s1")
Srs2 <- Polygons(list(Sr2), "s2")
SpP <- SpatialPolygons(list(Srs1, Srs2), 1:2)

SpP@polygons[[1]]@Polygons[[1]]@coords

##      [,1] [,2]
## [1,]    2    2
## [2,]    1    4
## [3,]    4    5
## [4,]    4    3
## [5,]    2    2

Sr1@coords
##      [,1] [,2]
## [1,]    2    2
## [2,]    4    3
## [3,]    4    5
## [4,]    1    4
## [5,]    2    2


SpP@polygons[[2]]@Polygons[[1]]@coords
##      [,1] [,2]
## [1,]    5    2
## [2,]    2    2
## [3,]    4    3
## [4,]    5    2

Sr2@coords
##      [,1] [,2]
## [1,]    5    2
## [2,]    4    3
## [3,]    2    2
## [4,]    5    2