You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R的sf包中计算st_length()时如何保留州名标识符

解决方法一:直接用st_distance计算(更简洁)

不用st_connect绕弯,直接用sf的st_distance函数就能在保留州名的前提下计算距离。修改后的代码如下:

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

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

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

# 给原数据框新增距离列,自动对应州名
us_with_dist <- us |>
  mutate(
    dist_to_kentucky = st_distance(geometry, kentucky$geometry, by_element = TRUE)
  )

# 输出州名和对应的距离
us_with_dist |>
  select(name, dist_to_kentucky) |>
  as.data.frame()

这里by_element = TRUE参数是关键,它会让每个州的质心与肯塔基的质心逐一配对计算距离,结果直接作为新列绑定到原数据框,完美保留州名和其他属性。

解决方法二:基于st_connect保留属性

如果一定要用st_connect,可以在计算长度前保留原数据的属性,再提取需要的字段:

dist_kentucky <- st_connect(us, kentucky) |>
  mutate(distance = st_length(.)) |> # 计算连线长度作为距离
  select(name, distance) # 只保留州名和距离列

as.data.frame(dist_kentucky)

st_connect会默认继承左边对象(也就是us)的属性列,所以计算完长度后直接选择name和新生成的distance列即可,不用再担心行顺序匹配问题。

内容的提问来源于stack exchange,提问作者johnny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 23:02:47