I have a dataframe (addresses) that has Latitude / Longitude information for 6 locations. I've also added (for illustrative purposes) the country in which this location actually belongs to (I don't have this in my real data). I then convert this dataframe to sf object (addresses_sf) using the st_as_sf function.
I then get the sf object of the Canadian borders via the rnaturalearth package and save this as can.
I want to determine which entries in address_sf are in Canada so I use the st_intersection function from the sf package.
Unfortunately, when this runs, it only identifies the 2nd entry (45.41126, -75.70591) as being in the Canadian borders and fails to identify the remaining 3 entries in the results.
I've attached some reproducible code below in the hopes it may identify what I'm doing wrong...
## Load necessary libraries
library(tidyverse)
library(rnaturalearth)
library(sf)
## Create data
addresses <- tibble::tribble(
~lat, ~lon, ~country,
43.77264, -88.4462, "usa",
45.41126, -75.70591, "canada",
42.235, -83.06181, "canada",
45.38441, -70.84368, "canada",
42.11125, -83.1107, "canada",
44.74441, -74.86597, "usa"
)
## Convert to sf
addresses_sf <- addresses %>%
rowid_to_column() %>%
st_as_sf(coords = c("lon", "lat"), crs = 4326)
## Get Canadian borders
can <- rnaturalearth::ne_countries(country = "Canada", returnclass = "sf") %>%
select(name) %>%
st_transform(crs = 4326)
## Determine which entries are in Canada
sf::st_intersection(addresses_sf, can)
Update:
Thanks to @Ray for highlighting the error in the above script as being one of not having adequate resolution. I updated the call to rnaturalearth with the line below and the code is now functioning as expected.
## Get Canadian borders
can <- rnaturalearth::ne_countries(country = "Canada", scale = "large", returnclass = "sf") %>%
select(name) %>%
st_transform(crs = 4326)
