Package sp
provides a number of classes for different spatial concepts (points, lines, polygons). For some classes, accessing feature coordinates is straightforward, e.g. SpatialLines
. All examples were taken from respective class help pages.
l1 = cbind(c(1,2,3),c(3,2,2))
l1a = cbind(l1[,1]+.05,l1[,2]+.05)
l2 = cbind(c(1,2,3),c(1,1.5,1))
Sl1 = Line(l1)
Sl1a = Line(l1a)
Sl2 = Line(l2)
S1 = Lines(list(Sl1, Sl1a), ID="a")
S2 = Lines(list(Sl2), ID="b")
Sl = SpatialLines(list(S1,S2))
coordinates(Sl)
# [prints a list of two with corresponding segments]
For SpatialPolygons
, coordinates()
returns polygon centers as demonstrated below.
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)))
Sr3 = Polygon(cbind(c(4,4,5,10,4),c(5,3,2,5,5)))
Sr4 = Polygon(cbind(c(5,6,6,5,5),c(4,4,3,3,4)), hole = TRUE)
Srs1 = Polygons(list(Sr1), "s1")
Srs2 = Polygons(list(Sr2), "s2")
Srs3 = Polygons(list(Sr3, Sr4), "s3/4")
SpP = SpatialPolygons(list(Srs1,Srs2,Srs3), 1:3)
coordinates(SpP)
[,1] [,2]
[1,] 2.696970 3.545455
[2,] 3.666667 2.333333
[3,] 6.133333 3.933333
Is there a handy function in common packages that would extract feature coordinates? I have come up with a function for SpatialPolygons
, but I'm looking for something that has been better tested and is consistent, perhaps even across most/all sp
classes.
getEdges <- function(x) {
stopifnot(class(x) == "SpatialPolygons")
lapply(x@polygons, function(y) {
y@Polygons[[1]]@coords
})
}
getEdges(SpP)
# [returns a list of three, coordinates in a matrix]
@property
to extract stuff. This is the internal organisation of the object, which might change without notice. – Salvador