Reputation: 43
I am newbie to SF and stack, hope my question is clear enough. I was able to create a set of lines connecting 1 point to a set of points all over the US. The I can read the US counties into multipolygons. My goal is to find and geolocate all the points where the lines I created cross the county borders.
So far I was able to create the lines from the points:
points_to_lines <- dt %>%
st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
group_by(lineid) %>%
summarize(do_union = FALSE) %>% lineid
st_cast("LINESTRING")
This is the head of the lines
Simple feature collection with 1628 features and 1 field
geometry type: LINESTRING
dimension: XY
bbox: xmin: 30.1127 ymin: -91.32484 xmax: 37.23671 ymax: -82.31262
epsg (SRID): 4326
proj4string: +proj=longlat +datum=WGS84 +no_defs
# A tibble: 1,628 x 2
lineid geometry
<int> <LINESTRING [°]>
1 1 (33.51859 -86.81036, 36.16266 -86.7816)
2 2 (33.51859 -86.81036, 34.61845 -82.47791)
This is the head of the county dataset.
Reading layer `US_county_1930_conflated' from data source `~/county_gis/1930' using driver `ESRI Shapefile'
Simple feature collection with 3110 features and 18 fields
geometry type: MULTIPOLYGON
dimension: XY
bbox: xmin: -7115608 ymin: -1337505 xmax: 2258244 ymax: 4591848
epsg (SRID): NA
proj4string: +proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=37.5 +lon_0=-96 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs
Very naively I have tried to give them both the same set of coordinates, and then st_intersects them. The non sparse matrix seams to say that all the lines intersect only one county.
gis1930_p <- st_set_crs(gis1930, 4326) %>% st_transform(4326)
st_intersects(points, gis1930_p, sparse=FALSE)
I also plot the lines on top of the counties but only the map of the US counties is mapped.
plot(gis1930_p[0], reset = FALSE)
plot(points[0], add = TRUE)
Any help would be greatly appreciated and please let me know if I can provide any additional details.
Upvotes: 4
Views: 2275
Reputation: 3403
You didn't provide your data so I am going to use the dataset provided in: https://gis.stackexchange.com/a/236922/32531
The main thing you need is the st_intersection
function:
library(sf)
line_1 <- st_as_sfc("LINESTRING(458.1 768.23, 455.3 413.29, 522.3 325.77, 664.8 282.01, 726.3 121.56)")
poly_1 <- st_as_sfc("MULTIPOLYGON(((402.2 893.03, 664.8 800.65, 611.7 666.13, 368.7 623.99, 215.1 692.06, 402.2 893.03)), ((703.9 366.29, 821.2 244.73, 796.1 25.93, 500.0 137.76, 703.9 366.29)))")
pnts <- st_intersection(line_1,
st_cast(poly_1, "MULTILINESTRING", group_or_split = FALSE))
plot(poly_1)
plot(line_1, add = TRUE)
plot(pnts, add = TRUE, col = "red", pch = 21)
Upvotes: 2