The error is occurring because the ID_2
column does not exist in the BRmap
object, as the error message is reporting.
When reading the downloaded file from the indicated page, we can verify that none of its columns are named ID_2
, but there is the column GID_2
(I do not know if it's really what I want to use).
BRmap <- readRDS("gadm36_BRA_2_sp.rds")
names(BRmap)
[1] "GID_0" "NAME_0" "GID_1" "NAME_1" "NL_NAME_1" "GID_2"
[7] "NAME_2" "VARNAME_2" "NL_NAME_2" "TYPE_2" "ENGTYPE_2" "CC_2"
[13] "HASC_2"
Something that helps a lot debug the codes built with the pipe operator ( %>%
) is to run the code that goes to one pipe, and then to the next one and so on. This helps to identify where the error is. In this case the error is already in the first line.
In addition, I recommend removing the line with mutate(...)
, since the IDs are not numeric, and converting them to integers will only have NA
in the entire column.
head(BRmap$GID_2)
[1] "BRA.1.1_1" "BRA.1.2_1" "BRA.1.3_1" "BRA.1.4_1" "BRA.1.5_1" "BRA.1.6_1"
Finally, we have:
library(dplyr)
PaísX <- ggplot2::fortify(BRmap, region = "GID_2") %>%
full_join(BRmap@data, by =c("id" = "GID_2")) %>%
select(c(id, long, lat, order, hole, piece, group, NAME_2))