user2837821
user2837821

Reputation: 21

Can't change the coordinates of a SpatialPolygonsDataFrame in R

This is my program:

library(sp)
library(RColorBrewer)

#get spatial data for Spain on region level
con <- url("http://gadm.org/data/rda/ESP_adm1.RData")
print(load(con))
close(con)
# plot Spain with colors
col = c("blue","blue","blue","blue","blue","blue","blue","blue","blue",
        "blue","blue","blue","blue","blue","blue","blue","red","red")
spplot(gadm, "NAME_1", col.regions=col, main="Regiones de España",
       colorkey=F, lwd=.4, col="black")

What I get when I run is what I am looking for, but I want to change the islands in the south west (Islas Canarias) to be closer to Spain country. I don't know what to do to change the coordinates of the islands. I just know they are here:

gadm[14,]

I try to make changes for example here:

gadm[14,]@polygons[[1]]@Polygons[[1]]@coords

but I get the message: no method for coercing this S4 class to a vector

Upvotes: 2

Views: 882

Answers (1)

Valentin_Ștefan
Valentin_Ștefan

Reputation: 6416

One could also try the sf package - CRAN link here

The GADM data URL seems deprecated now, but one can manually download the RDS file containing the SpatialPolygonsDataFrame for Spain from http://gadm.org/.

library(sf)
spain <- readRDS(file = "ESP_adm1.rds") # downloaded from http://gadm.org/

# convert from sp to sf object
spain_sf <- st_as_sf(spain)

# Change the coordinates of Canary Islands - the 14th geometry of spain_sf,
# itself with 20 polygons, check str(st_geometry(spain_sf)[[14]])
# Will shift them closer to mainland Spain.
# The added values are degrees because the CRS is unprojected
# (e.g. add 10 to longitudes and 6 to latitudes)
for (i in 1:length(st_geometry(spain_sf)[[14]])) {
  st_geometry(spain_sf)[[14]][[i]][[1]][, 1] <- st_geometry(spain_sf)[[14]][[i]][[1]][, 1] + 10
  st_geometry(spain_sf)[[14]][[i]][[1]][, 2] <- st_geometry(spain_sf)[[14]][[i]][[1]][, 2] + 6
}

# plot to check
par(omi=c(0,0,0,2)) # make some space to the right for the legend
plot(spain_sf["NAME_1"], 
     axes = TRUE, 
     graticule = st_crs(spain_sf))
# dev.off() # resets par()

enter image description here

Upvotes: 1

Related Questions