Search code examples
rpolygonspatial

R - Rename ID names of a spatial object


My goal is to change the ID names of a SpatialPolygon object. I know how to access the ID names but I'm stuck to rename them.

Here is an example (it's a SpatialPolygonDataFrame but in my 'real' case it's a SpatialPolygon, so without the necessary link between polygons and the data frame) :

library(rgdal)
library(rgeos)
library(sp)
library(maptools)

data(wrld_simpl)
mymap.sp <- wrld_simpl[which(wrld_simpl$ISO3 == "ATG" |
                             wrld_simpl$ISO3 == "BRA" |
                             wrld_simpl$ISO3 == "FRA" |
                             wrld_simpl$ISO3 == "CIV"), ]

# access to the ID names
sapply(slot(mymap.sp, "polygons"), function(x) slot(x, "ID"))
[1] "ATG" "BRA" "FRA" "CIV"

Suppose I want to replace these ID names by "1", "2", "3", "4".


Solution

  • If performance is not an issue, you can do this in a for loop:

    new_IDs = paste0("ID", 1:4)
    for (i in 1:length(slot(mymap.sp, "polygons"))){
      slot(slot(mymap.sp, "polygons")[[i]], "ID") = new_IDs[i]
    }