Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading