Last active
June 25, 2018 10:45
-
-
Save stijnvanhoey/7b51017718834f150f781a256292904e to your computer and use it in GitHub Desktop.
Comparison of spatial join (points within polygon) with `sp` or `sf` package
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(rgdal) | |
library(tidyverse) | |
library(leaflet) | |
# read point data as data.frame/tibble | |
# example data downloaded on GBIF: | |
# https://www.gbif.org/dataset/258c9ce5-1bda-4001-a192-347c9e7fb186 | |
# https://doi.org/10.15468/dl.etabvv | |
invasive_species <- read_tsv("./invasive_crabs.csv") %>% | |
filter(!is.na(decimallongitude), !is.na(decimallatitude)) | |
#### sp package #### | |
library(sp) | |
# read spatial data | |
eugrid <- readOGR("./EUgrid10.geojson") | |
# convert dat.frame to spatial data.frame | |
crs_wgs84 <- CRS("+init=epsg:4326") | |
coord <- invasive_species %>% | |
select(decimallongitude, decimallatitude) | |
invasive_spatial <- SpatialPointsDataFrame(coord, | |
data = invasive_species, | |
proj4string = crs_wgs84) | |
# spatial JOIN: over | |
invasive_eugrid10 <- over(invasive_spatial, spTransform(eugrid, crs_wgs84)) | |
invasive_species_eugrid10 <- bind_cols(invasive_species, | |
invasive_eugrid10) | |
#### sf package #### | |
library(sf) | |
# read spatial data | |
eugrid <- st_read("./EUgrid10.geojson") %>% | |
st_transform(crs = 31370) | |
# convert data.frame to spatial data.frame | |
invasive_spatial <- st_as_sf(invasive_species, | |
coords = c("decimallongitude", | |
"decimallatitude"), | |
crs = 4326) %>% | |
st_transform(crs = 31370) | |
# spatial JOIN: st_join | |
invasive_eugrid10 <- st_join(invasive_spatial, eugrid, | |
join = st_within, left = TRUE) %>% | |
select(-EofOrigin, -NofOrigin) # exclude the EofOrigin NofOrigin columns |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment