Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

geo_join

Easily merge a data frame to a spatial data frame


Description

The pages of StackOverflow are littered with questions about how to merge a regular data frame to a spatial data frame in R. The merge function from the sp package operates under a strict set of assumptions, which if violated will break your data. This function wraps a couple StackOverflow answers I've seen that work in a friendlier syntax.

Usage

geo_join(spatial_data, data_frame, by_sp, by_df, by = NULL, how = "left")

Arguments

spatial_data

A spatial data frame to which you want to merge data.

data_frame

A regular data frame that you want to merge to your spatial data.

by_sp

The column name you'll use for the merge from your spatial data frame.

by_df

The column name you'll use for the merge from your regular data frame.

by

(optional) If a named argument is supplied to the by parameter, geo_join will assume that the join columns in the spatial data and data frame share the same name.

how

The type of join you'd like to perform. The default, 'left', keeps all rows in the spatial data frame, and returns NA for unmatched rows. The alternative, 'inner', retains only those rows in the spatial data frame that match rows from the target data frame.

Value

a SpatialXxxDataFrame object

Examples

## Not run: 

library(rnaturalearth)
library(WDI)
library(tigris)

dat <- WDI(country = "all", indicator = "SP.DYN.LE00.IN", start = 2012, end = 2012)

dat$SP.DYN.LE00.IN <- round(dat$SP.DYN.LE00.IN, 1)

countries <- ne_countries()

countries2 <- geo_join(countries, dat, 'iso_a2', 'iso2c')

nrow(countries2)

## [1] 177

countries3 <- geo_join(countries, dat, 'iso_a2', 'iso2c', how = 'inner')

nrow(countries3)

## [1] 169


## End(Not run)

tigris

Load Census TIGER/Line Shapefiles

v1.0
MIT + file LICENSE
Authors
Kyle Walker [aut, cre], Bob Rudis [ctb]
Initial release
2020-07-13

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.