library(sf)
library(spData)
library(tidyverse)

We will use an sf object north_america with country codes (iso_a2), names and geometries, as well as a data.frame object wb_north_america containing information about urban population and unemployment for three countries. Note that north_america contains data about Canada, Greenland and the United States but the World Bank dataset (wb_north_america) contains information about Canada, Mexico and the United States:

north_america = world %>%
  filter(subregion == "Northern America") %>%
  dplyr::select(iso_a2, name_long)
north_america$name_long
## [1] Canada        United States Greenland    
## 177 Levels: Afghanistan Albania Algeria Angola Antarctica ... Zimbabwe
wb_north_america = worldbank_df %>% 
  filter(name %in% c("Canada", "Mexico", "United States")) %>%
  dplyr::select(name, iso_a2, urban_pop, unemploy = unemployment)

We will use a left join to combine the two datasets. Left joins are the most commonly used operation for adding attributes to spatial data, as they return all observations from the left object (north_america) and the matched observations from the right object (wb_north_america) in new columns. Rows in the left object without matches in the right (Greenland in this case) result in NA values.

To join two objects we need to specify a key. This is a variable (or a set of variables) that uniquely identifies each observation (row). The by argument of dplyr’s join functions lets you identify the key variable. In simple cases, a single, unique variable exist in both objects like the iso_a2 column in our example (you may need to rename columns with identifying information for this to work):

left_join1 = north_america %>% 
  left_join(wb_north_america, by = "iso_a2")
## Warning: Column `iso_a2` joining factor and character vector, coercing into
## character vector

This has created a spatial dataset with the new variables added. The utility of this is shown in Figure @ref(fig:unemploy), which shows the unemployment rate (a World Bank variable) across the countries of North America.

The unemployment rate (taken from World Bank statistics) in Canada and the United States to illustrate the utility of joining attribute data on to spatial datasets.

The unemployment rate (taken from World Bank statistics) in Canada and the United States to illustrate the utility of joining attribute data on to spatial datasets.

It is also possible to join objects by different variables. Both of the datasets have variables with names of countries, but they are named differently. The north_america has a name_long column and the wb_north_america has a name column. In these cases a named vector, such as c("name_long" = "name"), can specify the connection:

left_join2 = north_america %>% 
  left_join(wb_north_america, by = c("name_long" = "name"))
## Warning: Column `name_long`/`name` joining factor and character vector,
## coercing into character vector
names(left_join2)
## [1] "iso_a2.x"  "name_long" "iso_a2.y"  "urban_pop" "unemploy"  "geom"

Note that the result contains two duplicated variables - iso_a2.x and iso_a2.y because both x and y objects have the column iso_a2. This can be solved by specifying all the keys:

left_join3 = north_america %>% 
  left_join(wb_north_america, by = c("iso_a2", "name_long" = "name"))
## Warning: Column `iso_a2` joining factor and character vector, coercing into
## character vector
## Warning: Column `name_long`/`name` joining factor and character vector,
## coercing into character vector

Joins also work when a data frame is the first argument. This keeps the geometry column but drops the sf class, returning a data.frame object.

# keeps the geom column, but drops the sf class
left_join4 = wb_north_america %>%
  left_join(north_america, by = c("iso_a2"))
## Warning: Column `iso_a2` joining character vector and factor, coercing into
## character vector
class(left_join4)
## [1] "tbl_df"     "tbl"        "data.frame"

On the other hand, it is also possible to remove the geometry column of left_join4 using base R functions or dplyr. Here, this is this simple because the geometry column is just another data.frame column and no longer the sticky geometry column of an sf object (see also Chapter @ref(spatial-class)):

# base R
left_join4_df = subset(left_join4, select = -geom)
# or dplyr
left_join4_df = left_join4 %>% dplyr::select(-geom)
left_join4_df
## # A tibble: 3 x 5
##   name          iso_a2 urban_pop unemploy name_long    
##   <chr>         <chr>      <dbl>    <dbl> <fct>        
## 1 Canada        CA      29014612     6.91 Canada       
## 2 Mexico        MX      98099040     4.81 <NA>         
## 3 United States US     259460378     6.17 United States
class(left_join4_df)
## [1] "tbl_df"     "tbl"        "data.frame"

In contrast to left_join(), inner_join() keeps only observations from the left object (north_america) where there are matching observations in the right object (wb_north_america). All columns from the left and right object are still kept:

inner_join1 = north_america %>% 
  inner_join(wb_north_america, by = c("iso_a2", "name_long" = "name"))
## Warning: Column `iso_a2` joining factor and character vector, coercing into
## character vector
## Warning: Column `name_long`/`name` joining factor and character vector,
## coercing into character vector
inner_join1$name_long
## [1] "Canada"        "United States"