3

I am trying to bind a dataframe containing polygon centroids to the polygon attributes.

Here's what I've done so far to create the centroids:

library(rgdal)
library(PBSmapping)
library(maptools)
library(sp)

gisCentroids<-coordinates(gisPolygons)

I am wanting to combine the resultant centroids to the attribute data from gisPolygons. How do I go about achieving this? I have tried over from sp package but it does not seem to work giving me error messages. The code used is shown below:

ID<-over(SpatialPoints(gisCentroids),gisPolygons)
CentroidPolys<-cbind(gisCentroids,gisPolygons)

I want to do further intersection and overlap analyses once I have the centroids information bound to the polygon attributes.

Any suggestions?

1 Answer 1

6

Load libraries and example data

# Load libraries
library('raster')
library('geosphere')
library('mapview') # incredible interactive map visualization in R

# Get SpatialPolygonsDataFrame object example
polygons <- getData('GADM', country = 'URY', level = 1)

Plot example data

# Plot Polygons
mapview(polygons)

plotPolys

# Get polygons centroids
centroids <- as.data.frame(centroid(polygons))
colnames(centroids) <- c("lon", "lat") 
centroids <- data.frame("ID" = 1:nrow(centroids), centroids)

# Create SpatialPointsDataFrame object
coordinates(centroids) <- c("lon", "lat") 
proj4string(centroids) <- proj4string(polygons) # assign projection

Plot polygons + centroids

# Plot Polygons + Centroids
mapview(polygons) + mapview(centroids)

plotPolysAndCentroids

Getting attributes

# Get polygons attribute for each centroid point 
centroids@data <- sp::over(x = centroids, y = polygons, returnList = FALSE)

#class       : SpatialPointsDataFrame 
#features    : 19 
#extent      : -57.76437, -54.02354, -34.82602, -30.54739  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0 
#variables   : 13
#names       : OBJECTID, ID_0, ISO,  NAME_0, ID_1,         NAME_1, HASC_1, CCN_1, CCA_1,       TYPE_1,  ENGTYPE_1, NL_NAME_1,  VARNAME_1 
#min values  :        1,  245, URY, Uruguay,    1,        Artigas,  UY.AR,    NA,      , Departamento, Department,          ,            
#max values  :       19,  245, URY, Uruguay,   19, Treinta y Tres,  UY.TT,    NA,      , Departamento, Department,          , Montevidéu 

Final plot

# Plot centroids with data (click on point to see the information)
mapview(centroids)

centroidsWithAttributes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.