Search code examples
rr-sfr-mapview

Connecting two sets of coordinates to create lines using sf/mapview


I have a dataset where a bird captured in one location (Blong, Blat) then encountered again in another (Elong, Elat). These coordinates are in a lat/long format, and I'd like to connect the capture and encounter locations with a line and plot them in mapview.

In the data below, each row is an individual bird with its capture/encounter coordinates, and the flyway that it belongs to (which I would like to use to color the lines in mapview.

dat <- structure(list(Blong = c(-75.58333, -76.08333, -81.08333, -94.25, 
    -75.41667, -99.41667, -77.41667, -116.08333, -89.58333, -77.58333
    ), Blat = c(37.58333, 40.58333, 42.75, 41.91667, 38.25, 28.25, 
    38.91667, 43.58333, 44.25, 38.91667), Elong = c(-65.91667, -75.75, 
    -80.58333, -95.41667, -73.58333, -89.41667, -77.58333, -116.41667, 
    -96.41667, -77.41667), Elat = c(45.91667, 40.58333, 42.75, 29.75, 
    45.58333, 48.25, 38.75, 43.58333, 34.08333, 38.91667), Flyway = structure(c(2L, 
    2L, 2L, 1L, 2L, 2L, 2L, 3L, 2L, 2L), .Label = c("Central", "Eastern", 
    "West"), class = "factor")), .Names = c("Blong", "Blat", "Elong", 
    "Elat", "Flyway"), row.names = c(NA, -10L), class = c("tbl_df", 
    "tbl", "data.frame"))

A look at the data:

# A tibble: 10 x 5
    Blong  Blat  Elong  Elat Flyway 
    <dbl> <dbl>  <dbl> <dbl> <fct>  
 1  -75.6  37.6  -65.9  45.9 Eastern
 2  -76.1  40.6  -75.8  40.6 Eastern
 3  -81.1  42.8  -80.6  42.8 Eastern
 4  -94.2  41.9  -95.4  29.8 Central
 5  -75.4  38.2  -73.6  45.6 Eastern
 6  -99.4  28.2  -89.4  48.2 Eastern
 7  -77.4  38.9  -77.6  38.8 Eastern
 8 -116.   43.6 -116.   43.6 West   
 9  -89.6  44.2  -96.4  34.1 Eastern
10  -77.6  38.9  -77.4  38.9 Eastern

I've looked a few examples, but haven't found one that looks quite like my data set.


Solution

  • The tricky thing is to create a valid LINESTRING object from the coordinate pairs in wide format. sf expects linestring coordinates in rows of a matrix. Here's a way that works. The sfc column of a sf object is a list so here we use lapply to loop over the rows of the data you provided.

    library(sf)
    library(mapview)
    
    b = dat[, c("Blong", "Blat")]
    names(b) = c("long", "lat")
    e = dat[, c("Elong", "Elat")]
    names(e) = c("long", "lat")
    
    dat$geometry = do.call(
      "c", 
      lapply(seq(nrow(b)), function(i) {
        st_sfc(
          st_linestring(
            as.matrix(
              rbind(b[i, ], e[i, ])
            )
          ),
          crs = 4326
        )
      }))
    
    dat_sf = st_as_sf(dat)
    
    mapview(dat_sf, zcol = "Flyway")