Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting lines between two sf POINT features in r

Tags:

r

sf

I have two spatial features:

library(sf)

points1 <- data.frame(foo = seq(15, 75, 15), 
                     long = c(-85, -80, -78, -75, -82), 
                     lat = c(34, 36, 37, 38, 35)) %>% 
    st_as_sf(coords = c('long', 'lat'), crs = 4326) 

points2 <- data.frame(bar = seq(15, 75, 15), 
                     long = c(85, 80, 78, 75, 82), 
                     lat = c(30, 32, 34, 36, 38)) %>% 
    st_as_sf(coords = c('long', 'lat'), crs = 4326) 

cbind(points1, points2) -> df

This gives:

  foo bar       geometry    geometry.1
1  15  15 POINT (-85 34) POINT (85 30)
2  30  30 POINT (-80 36) POINT (80 32)
3  45  45 POINT (-78 37) POINT (78 34)
4  60  60 POINT (-75 38) POINT (75 36)
5  75  75 POINT (-82 35) POINT (82 38)

I'd like to draw a line between pairs of points within df - so from a POINT in geometry to a POINT in geometry.1. I have tried to cast the POINTs to a LINESTRING as follows:

df %>% summarise(do_union=F) %>% st_cast("LINESTRING") %>% plot()

, but this doesn't seem to work. I get a continuous line, when what I want is five separate lines.

like image 977
Anthony W Avatar asked Sep 28 '19 21:09

Anthony W


1 Answers

Use mapply to create a line string by unioning the points pairwise from the geometry columns:

> st_sfc(mapply(function(a,b){st_cast(st_union(a,b),"LINESTRING")}, df$geometry, df$geometry.1, SIMPLIFY=FALSE))
Geometry set for 5 features 
geometry type:  LINESTRING
dimension:      XY
bbox:           xmin: -85 ymin: 30 xmax: 85 ymax: 38
epsg (SRID):    NA
proj4string:    NA
LINESTRING (-85 34, 85 30)
LINESTRING (-80 36, 80 32)
LINESTRING (-78 37, 78 34)
LINESTRING (-75 38, 75 36)
LINESTRING (-82 35, 82 38)

At first I thought st_union(geom1, geom2, by_feature=TRUE) would be sufficient to do most of the work but (as documented) the by_feature is ignored with two arguments to st_union and the output is a union of each of the 25 pairs of features from geom1 and geom2.

Here's a slower, kludgier way via a matrix of coordinates:

> coords = cbind(st_coordinates(df$geometry), st_coordinates(df$geometry.1))

Construct linestrings by row:

> linestrings = st_sfc(
     lapply(1:nrow(coords),
           function(i){
             st_linestring(matrix(coords[i,],ncol=2,byrow=TRUE))
           }))

See:

> plot(linestrings)

enter image description here

if you want to replace the (first) point geometry in your data frame with the lines then:

> st_geometry(df) = linestrings
like image 200
Spacedman Avatar answered Sep 27 '22 15:09

Spacedman