[英]Calculating distance between projected coordinates within individuals (adding distance column?)
I have a movement dataset with different individuals and projected coordinates.我有一个具有不同个体和投影坐标的运动数据集。 The coordinates were projected into UTM using the following code:
使用以下代码将坐标投影到 UTM 中:
coordinates(data) = ~x+y #turns data into spatial data frame
proj4string(data) <- CRS("+init=epsg:4326")
data <- spTransform(data, CRS("+init=epsg:5321")) #denotes what CRS to use, this changes the data into UTMs from lat/long, which projects the data
data <- as.data.frame(data)
I would like to calculate the distance in meters between coordinates within individuals.我想计算个体内部坐标之间的距离(以米为单位)。 I'm okay with a pretty large margin of error as long as it is consistent between points.
只要点之间保持一致,我就可以接受相当大的误差范围。
Here is a sample of my dataset:这是我的数据集示例:
ID x y
Bear1 459486.4 7181992
Bear1 459652.6 7181904
Bear1 459661.5 7181880
Bear2 459604.7 7181898
Bear2 459639.6 7181894
Bear2 459565.1 7181960
Optimally, I'd love a distance column added to this dataset, showing the distance within points.最理想的是,我希望在此数据集中添加一个距离列,以显示点内的距离。
Please find below a reprex that shows a solution with the sf
package.请在下面找到一个 reprex,它显示了
sf
包的解决方案。
If I am not wrong, the data you provide are already in EPSG:5321.如果我没记错的话,你提供的数据已经在EPSG:5321中了。 Assuming this, you only need to enter the following lines of code to get a distance matrix between all the possible pairs of points.
假设这样,您只需要输入以下几行代码即可获得所有可能的点对之间的距离矩阵。
Reprex正品
library(sf)
data <- st_as_sf(data, coords = c("x", "y"), crs = 5321)
distances <- st_distance(data)
distances
#> Units: [m]
#> [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,] 0.00000 188.05967 207.85574 151.09894 181.86325 84.95699
#> [2,] 188.05967 0.00000 25.59707 48.27432 16.40122 103.88575
#> [3,] 207.85574 25.59707 0.00000 59.58389 25.99250 125.27155
#> [4,] 151.09894 48.27432 59.58389 0.00000 35.12848 73.56738
#> [5,] 181.86325 16.40122 25.99250 35.12848 0.00000 99.53015
#> [6,] 84.95699 103.88575 125.27155 73.56738 99.53015 0.00000
Created on 2021-10-27 by the reprex package (v0.3.0)由reprex 包(v0.3.0) 于 2021 年 10 月 27 日创建
If you want to start from scratch, that is, from geographic coordinates (ie EPSG = 4326), you have to proceed as follows:如果要从头开始,即从地理坐标(即EPSG = 4326)开始,则必须按照以下步骤进行:
library(sf)
data <- st_as_sf(data, coords = c("x", "y"), crs = 4326)
data <- st_transform(data, crs = 5321)
distances <- st_distance(data)
distances
data <- data.frame(ID = c("Bear1", "Bear1", "Bear1", "Bear2", "Bear2", "Bear2"),
x = c(459486.4, 459652.6, 459661.5, 459604.7, 459639.6, 459565.1),
y = c(7181992, 7181904, 7181880, 7181898, 7181894, 7181960))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.