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

在R的sf包中如何让距离矩阵显示个体ID而非行号?

解决方法

直接为距离矩阵的行列设置自定义名称即可,修改后的完整代码如下:

library(sf)

species <- data.frame(longitude = c(-106.425668, -96.111617, -96.5,-96.5, -96.5, -96.5), 
                      latitude = c(23.18127, 15.779873, 19.68, 19.68, 19.68, 19.68), 
                      id = c("0-1","0-2","0-3","0-4","0-5","0-6"))

species_sf <- st_as_sf(species, coords = c("longitude", "latitude"), crs = 4326)

# 计算距离矩阵并设置行列名称
dist_matrix <- st_distance(species_sf)
dimnames(dist_matrix) <- list(species$id, species$id)

# 输出结果
dist_matrix

修改后的输出:

Units: [m]
        0-1      0-2      0-3      0-4      0-5      0-6
0-1       0 1357855.2 1098291.3 1098291.3 1098291.3 1098291.3
0-2 1357855       0.0  435620.5  435620.5  435620.5  435620.5
0-3 1098291  435620.5       0.0       0.0       0.0       0.0
0-4 1098291  435620.5       0.0       0.0       0.0       0.0
0-5 1098291  435620.5       0.0       0.0       0.0       0.0
0-6 1098291  435620.5       0.0       0.0       0.0       0.0

说明

st_distance()返回的是带单位的矩阵(units类对象),通过dimnames()可以直接为矩阵的行和列设置自定义标签,这里直接调用数据框中的id列就能替换默认的数字行号。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 18:33:23