英文:
How to obtain individual IDs in the matrix, instead of row names in R (sf package)?
问题
我获得了一个包含每个物种ID之间距离的矩阵。如何使矩阵显示个体的实际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)
st_distance(species_sf)
我的输出如下:
Units: [m]
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0 1357855.2 1098291.3 1098291.3 1098291.3 1098291.3
[2,] 1357855 0.0 435620.5 435620.5 435620.5 435620.5
[3,] 1098291 435620.5 0.0 0.0 0.0 0.0
[4,] 1098291 435620.5 0.0 0.0 0.0 0.0
[5,] 1098291 435620.5 0.0 0.0 0.0 0.0
[6,] 1098291 435620.5 0.0 0.0 0.0 0.0
我希望方括号显示实际的物种ID。
谢谢。
英文:
I obtained a matrix of distances between each species ID. How do I get the matrix to show the actual ID of individuals instead of row numbers?
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)
st_distance(species_sf)
My output is below:
Units: [m]
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0 1357855.2 1098291.3 1098291.3 1098291.3 1098291.3
[2,] 1357855 0.0 435620.5 435620.5 435620.5 435620.5
[3,] 1098291 435620.5 0.0 0.0 0.0 0.0
[4,] 1098291 435620.5 0.0 0.0 0.0 0.0
[5,] 1098291 435620.5 0.0 0.0 0.0 0.0
[6,] 1098291 435620.5 0.0 0.0 0.0 0.0
I want the square brackets to show actual species IDs.
Thank you.
答案1
得分: 3
你可以使用rownames()
和colnames()
来设置名称:
species_sf |>
st_distance() |>
`rownames<-`(species_sf$id) |>
`colnames<-`(species_sf$id)
#> 单位:[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
英文:
You can set names with rownames()
& colnames()
:
species_sf |>
st_distance() |>
`rownames<-`(species_sf$id) |>
`colnames<-`(species_sf$id)
#> 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论