There are several ways to get at all of the coordinates for a SpatialPolygonsDataFrame
or a SpatialLinesDataFrame
.
Each of these methods records the object and the part within the object from the source, albeit with subtle differences and different names.
Say p
is a SpatialPolygonsDataFrame
.
#1. coerce to points, then to data frame
# names are Lines.NR Lines.ID Line.NR coords.x1 coords.x2
## start here for polys
lin <- as(p, "SpatialLinesDataFrame")
## start here for lines
pts <- as.data.frame(as(lin, "SpatialPointsDataFrame"))
#2. convert to matrix
# names are object part cump hole x y
mpts <- raster::geom(p)
#3. convert to data frame
# names are long lat order hole piece id group
dpts <- ggplot2::fortify(p)
#4. convert to data frame
## names are object_ branch_ island_ order_ x_ y_
spts <- spbabel::sptable(p)
Each of these outputs can be used interchangeably as long as you deal with the different name conventions, and for raster::geom
remember that it's a matrix. (Actually the coercion one doesn't record the hole/island status so that is less useful depending on what's needed).
You can round trip the last one by
p2 <- spbabel::sp(spts, attr_tab = as.data.frame(p))
(There's an added bonus with spbabel
in that you get a 'raster-like' print for the object, but with the data in 'tibble' print form. )
you can use the raster::xyFromCell
function to get a matrix of coordinates from a vector of cell numbers, which you can cbind onto the extract (as the xyFromCell result is in exactly the same order as the vector provided)
I've used sf
but of course this works with readOGR etc.;
require(raster)
require(sf)
# make 2 dummy rasters for a dummy stack
r <- raster(xmn=0,xmx=10,ymn=0,ymx=10,res=1)
r[] <- sample(1:4,100,replace=T)
r2 <- raster(xmn=0,xmx=10,ymn=0,ymx=10,res=1)
r2[] <- sample(8:10,100,replace=T)
s <- stack(r,r2)
# make a triangle simple feature
s2 <- rbind(c(2.2,2.2), c(3.3,8.5), c(5.3,0.8), c(2.2,2.2))
s2.sf <-st_sfc(st_polygon(list(s2)))
s2.pol = st_sf(ID = "tr", s2.sf)
# extract values into data frame
ex.df <- as.data.frame(extract(s,s2.pol,cellnumbers=T))
# create coordinate columns using xyFromCell
ex.df.coords <- cbind(ex.df, xyFromCell(s,ex.df[,1]))
Best Answer
You can convert your raster to polygon then use
gCentroid
to extract the centroid. Here is an example taken from this answer