Search code examples
rpolygonraster

Extract coordinates of polygons centroids


I’d like to add the latitude and the longitude of all polygons’ centroids to the dataframe of a SpatialPolygonsDataFrame. However, since I’m not sure how to extract the polygons id when using gCentroid, I’m not sure how to do the merge (see 3rd line of code below). Is someone able to help me with this? Thanks a lot!

library(tidyverse)
library(rgeos)
ETH <- getData("GADM", country = "ETH", level = 3) # example of SpatialPolygonsDataFrame
cent <- as.data.frame(gCentroid(ETH, byid=TRUE)) # extraction of the coordinates of the polygons' centroids
ETH@data <- ETH@data %>% left_join(cent, by=?) # Here, I am not sure how to add the coordinates of the polygons' centroids to the dataframe.

Solution

  • You can use the id = parameter in gCentroid to choose the ID labels for each point. Select a column with unique entries from ETH to populate this. These get added as row names, so you can then use tibble::rownames_to_column to convert these to a column. This allows the left join:

    library(tidyverse)
    library(rgeos)
    
    ETH      <- getData("GADM", country = "ETH", level = 3) 
    cent     <- as.data.frame(gCentroid(ETH, byid = TRUE, id = ETH@data$GID_3))
    cent     <- tibble::rownames_to_column(cent, var = "GID_3")
    ETH@data <- ETH@data %>% left_join(cent, by = "GID_3")
    

    And we can show this by plotting the result, with the centroids as red points:

    plot(ETH)
    points(ETH@data$x, ETH@data$y, col = "red")
    

    enter image description here