Why am I unable to rename rnaturalearth data column?

31 Views Asked by At

I have retrieved the rnaturalearth data as sf class, and I am trying to rename one of the columns from "iso_a2" to "countryCode" to more easily join it with another dataset of mine. When I try to rename it using rename(), I am left with this error:

library(rnaturalearth)
library(dplyr)

baseBorderMap <- 
  ne_countries(returnclass = 'sf')

baseBorderMap <- rename(baseBorderMap, "countryCode" = "iso_a2")

Error in rename.sf(baseBorderMap, countryCode = "iso_a2") : internal error: can't find agr columns`

I was hoping to be able to join these two datasets through a renamed column, but because I am getting an error when trying to rename a column I know exists, I am unable to.

Why am I getting this error when I know that there is a column in the rnaturalearth data named "iso_a2"?

1

There are 1 best solutions below

0
L Tyrone On BEST ANSWER

It's a known bug with renaming columns in some sf objects. And that rnaturalearth dataset has more than a few 'foibles' to contend with. A workaround is to select() all the columns first:

library(rnaturalearth)
library(dplyr)

baseBorderMap <- ne_countries(returnclass = 'sf') %>%
  select(featurecla:geometry) %>%
  rename(countryCode = iso_a2)

select(baseBorderMap, countryCode)
# Simple feature collection with 177 features and 1 field
# Geometry type: MULTIPOLYGON
# Dimension:     XY
# Bounding box:  xmin: -180 ymin: -90 xmax: 180 ymax: 83.64513
# Geodetic CRS:  WGS 84
# First 10 features:
#    countryCode                       geometry
# 1           FJ MULTIPOLYGON (((180 -16.067...
# 2           TZ MULTIPOLYGON (((33.90371 -0...
# 3           EH MULTIPOLYGON (((-8.66559 27...
# 4           CA MULTIPOLYGON (((-122.84 49,...
# 5           US MULTIPOLYGON (((-122.84 49,...
# 6           KZ MULTIPOLYGON (((87.35997 49...
# 7           UZ MULTIPOLYGON (((55.96819 41...
# 8           PG MULTIPOLYGON (((141.0002 -2...
# 9           ID MULTIPOLYGON (((141.0002 -2...
# 10          AR MULTIPOLYGON (((-68.63401 -...