如何更正此代码以正确测量点之间的距离?

问题描述 投票:0回答:1

我正在处理动物运动数据集。我一直在尝试对移动距离进行编码,而不是仅使用 Excel 中的距离公式,因为我希望能够将该过程应用于可能更大的数据集。我发现这篇旧帖子(Calculate Daily Scaled Travel Distance for UTM Animal Movement Data in R)通常有效。这是我目前的进展:

library(sf)
library(readr)
library(dplyr)

## Load in the data and clean it to ensure correct format.
ToadDistCalc <- read_csv("Documents/RProjects/ToadMovement/ToadDistCalc.csv")
ToadDistCalc$DateTime <- as.POSIXct(ToadDistCalc$DateTime,
                                    format = "%Y-%m-%d %H:%M:%S",
                                    tz = "America/Jamaica")

## Make the data a spatial object. Look up what the correct EPSG is.
toad.so <- st_as_sf(
  ToadDistCalc,
  coords = c('X', 'Y'),
  crs = "EPSG+26918")

## Calculate distance. group_by attribute dependent on data.
toad.so <- toad.so %>%
  group_by(ID) %>%
  mutate(
    lead = geometry[row_number() + 1],
    dist = st_distance(geometry, lead, by_element = T),)

但是,当我检查数据时,移动距离被错误地分配给它们发生之前的日期。

如果我尝试通过将引导变量更改为 row_number() - 1 来解决此问题,我会收到此错误

enter image description here

更改变量名称的位置不会影响错误。我还想按天平均移动。我可以在 Excel 中轻松做到这一点,但我也想知道编码解决方案。

r distance
1个回答
0
投票

看起来您正在尝试计算每个蟾蜍 ID 变量中连续几何条目之间的距离。

让我们在英国网格系统上制作一个由 5 只蟾蜍组成的随机点样本数据集,每只蟾蜍有 20 个点。

> pts = st_as_sf(data.frame(x=runif(100), y=runif(100)), coords=1:2, crs="EPSG:27700")
> pts$ID = rep(1:5, each=20)

要计算几何中的连续距离,请使用

st_distance
但删除第一个参数中的最后一个元素和第二个参数中的第一个元素。在开头添加 0 即可获取在第一个点行驶的距离。然后您将点 1 与 2 进行比较,然后将 2 与 3 进行比较,依此类推。

succ.dist = function(toad){
   c(0,
     st_distance(
       toad$geometry[-nrow(toad)],
       toad$geometry[-1],
     by_element=TRUE))
 }

这适用于完整的数据框。但您希望将其应用于每个 ID 值以获取每个蟾蜍的距离。使用拆分-应用-组合策略:

step.distances = unlist(lapply(split(pts, pts$ID), succ.dist))

现在您可以将其添加到数据框中:

> pts$step.distances = step.distances
> head(pts)
Simple feature collection with 6 features and 2 fields
Geometry type: POINT
Dimension:     XY
Bounding box:  xmin: 0.08351158 ymin: 0.161554 xmax: 0.9587816 ymax: 0.7150356
Projected CRS: OSGB36 / British National Grid
                     geometry ID step.distances
1 POINT (0.1272845 0.4104881)  1      0.0000000
2  POINT (0.4923749 0.161554)  1      0.4418814
3  POINT (0.08351158 0.70452)  1      0.6796920
4   POINT (0.9587816 0.38298)  1      0.9324621
5 POINT (0.5181507 0.7150356)  1      0.5517396
6 POINT (0.3361486 0.4482891)  1      0.3229218
© www.soinside.com 2019 - 2024. All rights reserved.