This vignette provides some further detail on the Vector attribute joining section (see https://geocompr.robinlovelace.net/attr.html#vector-attribute-joining ) of the Geocomputation with R book.

This vignette requires the following packages to be installed and attached:

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
## Simple feature collection with 3 features and 2 fields
## geometry type:  MULTIPOLYGON
## dimension:      XY
## bbox:           xmin: -171.7911 ymin: 18.91619 xmax: -12.20855 ymax: 83.64513
## geographic CRS: WGS 84
## # A tibble: 3 x 3
##   iso_a2 name_long                                                          geom
##   <chr>  <chr>                                                <MULTIPOLYGON [°]>
## 1 CA     Canada       (((-122.84 49, -122.9742 49.00254, -124.9102 49.98456, -1…
## 2 US     United Stat… (((-122.84 49, -120 49, -117.0312 49, -116.0482 49, -113 …
## 3 GL     Greenland    (((-46.76379 82.62796, -43.40644 83.22516, -39.89753 83.1…
wb_north_america = worldbank_df %>% 
  filter(name %in% c("Canada", "Mexico", "United States")) %>%
  dplyr::select(name, iso_a2, urban_pop, unemploy = unemployment)
wb_north_america
## # A tibble: 3 x 4
##   name          iso_a2 urban_pop unemploy
##   <chr>         <chr>      <dbl>    <dbl>
## 1 Canada        CA      29014612     6.91
## 2 Mexico        MX      98099040     4.81
## 3 United States US     259460378     6.17

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")
left_join1
## Simple feature collection with 3 features and 5 fields
## geometry type:  MULTIPOLYGON
## dimension:      XY
## bbox:           xmin: -171.7911 ymin: 18.91619 xmax: -12.20855 ymax: 83.64513
## geographic CRS: WGS 84
## # A tibble: 3 x 6
##   iso_a2 name_long                                geom name   urban_pop unemploy
##   <chr>  <chr>                      <MULTIPOLYGON [°]> <chr>      <dbl>    <dbl>
## 1 CA     Canada     (((-122.84 49, -122.9742 49.00254… Canada  29014612     6.91
## 2 US     United St… (((-122.84 49, -120 49, -117.0312… Unite… 259460378     6.17
## 3 GL     Greenland  (((-46.76379 82.62796, -43.40644 … <NA>          NA    NA

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

Figure 1. 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.

Figure 1. 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"))
left_join2
## Simple feature collection with 3 features and 5 fields
## geometry type:  MULTIPOLYGON
## dimension:      XY
## bbox:           xmin: -171.7911 ymin: 18.91619 xmax: -12.20855 ymax: 83.64513
## geographic CRS: WGS 84
## # A tibble: 3 x 6
##   iso_a2.x name_long                            geom iso_a2.y urban_pop unemploy
##   <chr>    <chr>                  <MULTIPOLYGON [°]> <chr>        <dbl>    <dbl>
## 1 CA       Canada     (((-122.84 49, -122.9742 49.0… CA        29014612     6.91
## 2 US       United St… (((-122.84 49, -120 49, -117.… US       259460378     6.17
## 3 GL       Greenland  (((-46.76379 82.62796, -43.40… <NA>            NA    NA

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"))
left_join3
## Simple feature collection with 3 features and 4 fields
## geometry type:  MULTIPOLYGON
## dimension:      XY
## bbox:           xmin: -171.7911 ymin: 18.91619 xmax: -12.20855 ymax: 83.64513
## geographic CRS: WGS 84
## # A tibble: 3 x 5
##   iso_a2 name_long                                       geom urban_pop unemploy
##   <chr>  <chr>                             <MULTIPOLYGON [°]>     <dbl>    <dbl>
## 1 CA     Canada      (((-122.84 49, -122.9742 49.00254, -124…  29014612     6.91
## 2 US     United Sta… (((-122.84 49, -120 49, -117.0312 49, -… 259460378     6.17
## 3 GL     Greenland   (((-46.76379 82.62796, -43.40644 83.225…        NA    NA

Joins also work when a data frame is the first argument. However, for them to work we need to drop the sf class.

left_join4 = wb_north_america %>%
  left_join(st_drop_geometry(north_america), by = c("iso_a2"))
left_join4
## # A tibble: 3 x 5
##   name          iso_a2 urban_pop unemploy name_long    
##   <chr>         <chr>      <dbl>    <dbl> <chr>        
## 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)
## [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"))
inner_join1
## Simple feature collection with 2 features and 4 fields
## geometry type:  MULTIPOLYGON
## dimension:      XY
## bbox:           xmin: -171.7911 ymin: 18.91619 xmax: -52.6481 ymax: 83.23324
## geographic CRS: WGS 84
## # A tibble: 2 x 5
##   iso_a2 name_long                                       geom urban_pop unemploy
##   <chr>  <chr>                             <MULTIPOLYGON [°]>     <dbl>    <dbl>
## 1 CA     Canada      (((-122.84 49, -122.9742 49.00254, -124…  29014612     6.91
## 2 US     United Sta… (((-122.84 49, -120 49, -117.0312 49, -… 259460378     6.17