Easily merge a data frame to a spatial data frame
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.
geo_join(spatial_data, data_frame, by_sp, by_df, by = NULL, how = "left")
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. |
a SpatialXxxDataFrame
object
## 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)
Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.