I've read through many forums regarding this topic but I can't seem to adapt anything I've read to my particular question. Basically, I have a data frame of lat/lon values and all I want to do is test whether these coordinates exist within California.
Here is some example data:
library(tidyverse)
library(sf)
coords <- tribble(
~city, ~lon, ~lat,
LA, -118.2437, 34.0522,
SF, -122.4194, 37.7749,
SAC, -121.4944, 38.5816,
CHI, -87.6298, 41.8781,
NY, -74.0060, 40.7128
)
And here is a link to the shape files from the state website: CA Shape Files.
I think I'm close...
# read in shape data
cali <- read_sf("CA_State_TIGER2016.shp")
# convert coordinates to spatial point compatible data
coords_sf <- st_as_sf(coords, coords = c("lon", "lat"), crs = st_crs(cali))
From there, I assume I use st_contains
to test whether my cali
object contains the coordinates found in coords_sf
but I can't get it to work.
Any advice?
Thanks for your help!