Search code examples
rr-sfrnaturalearth

Keep identifiers when calculating st_length() in sf package in r


I want to calculate the distance from the centroid of every US state to the centroid of Kentucky. I achieve this using the following code:

library(rnaturalearth)
library(sf)
library(tidyverse)
library(nngeo)

us <- ne_states("United States of America", returnclass = "sf") |> 
  st_centroid()

kentucky <- us |> 
  filter(name == "Kentucky")

dist_kentucky <- st_connect(us, kentucky) |> 
  st_length() 

as.data.frame(dist_kentucky)

The problem now is that I'm unable to link the distance variable to the name of the state, although I assume that it's done row wise. How can I keep the names of the states when running st_length?


Solution

  • one approach:

    library(rnaturalearth)
    library(sf)
    library(nngeo)
    
    setNames(
      st_connect(us, kentucky) |> st_length(),
      us$name
    ) 
    

    or you could cbind the distances with state names, dplyr::mutate the us dataframe etc.