I am working with the world and worldbank_df datasets in the spData package in R, and am needing to subset my data and graph my results. I am selecting the columns "continents" and "urban_pop," dropping all NA values, grouping by continent, and summarizing the mean urban population of all continents. However, when I go to graph the results using the geom_sf call, I am getting an error:
Error in FUN(X[[i]], ...) : object 'mean_urban_pop' not found
I need to graph this data in a world map, but it's not working for me because the geom coordinates are not being transferred over to my new dataset.
How can I get these results graphed?
Note: The below coordinate system projected is the one that I must use.
Here is my code:
library(tidyverse)
library(sf)
library(spData)
library(ggplot2)
#Load in the data
world <- spData::world
wdb <- spData::worldbank_df
#Combine the data frames
wld_jn <- left_join(world, wdb, by = c('iso_a2', 'name_long' = 'name'))
#Reproject to required coordinate system. Obtained from: https://spatialreference.org/ref/sr-org/6/
wld_jn <- st_transform(wld_jn, '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs')
def_wld_jn <- st_set_crs(wld_jn, '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs')
#Graph mean urban population across continent:
wld_jn %>%
select(continent, urban_pop) %>%
drop_na() %>%
group_by(continent) %>%
summarise_at(vars(urban_pop), list(mean_urban_pop = mean)) %>%
ggplot(.) +
geom_sf(data = wld_jn, aes(fill = mean_urban_pop)) +
scale_fill_gradient2(midpoint = 285)+
guides(fill = guide_colorbar(title = "Population",
title.position = "bottom",
title.theme = element_text(size = 10,
face = "bold",
colour = "gray70",
angle = 0))) +
ggtitle("World Urban Population") +
theme(plot.title = element_text(hjust = 0.5))

