I have geom POINTs in two separate data frames. What I want to do is to connect points with a line (later on a map) so that's why I want to create Linestring for each pair of points from those data frames. I made it like this:
coordsCust <- table %>%
st_as_sf(coords = c("lonCust","latCust"), crs = 4326)
coordsApp <- table %>%
st_as_sf(coords = c("lonApp","latApp"), crs = 4326) %>%
st_geometry()
and Linestring:
lines <- st_sfc(mapply(function(a,b){
st_cast(st_union(a,b),"LINESTRING")},
coordsCust$geometry, coordsApp$geometry, SIMPLIFY=FALSE))
This code works, I can create Linestrings for each pair of points, row by row:
LINESTRING (14.035 51.65182, 14.33418 53.53346)
LINESTRING (20.42767 49.98073, 16.62978 52.31037)
LINESTRING (20.18762 50.03337, 16.62978 52.31037)
LINESTRING (19.04625 49.79234, 16.62978 52.31037)
LINESTRING (21.35808 50.92382, 16.62978 52.31037)
The issue is that for 30 000 rows this solution works really slow - about 21 seconds. Is there any other way to create linestrings from points? Something that works much faster? I searched for some solutions on the web but in vain. I've read something about converting sf to matrix and using pmap
but have no idea how to implement it here.
UPDATE: if I want to use sfheaders::sf_linestring function I need to join geometries from both datasets. I do it like this:
df <- cbind(coordsCust,coordsApp)
and the final data frame (I showed most important part of it) is shown below:
Unfortunately sf_linestring doesn't work properly on this dataframe. I need to create linestring between POINTs for each row separately as shown on the screen.