在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
相关产品推荐
相关产品推荐

