簡體   English   中英

使用mutate中的distm函數計算兩點之間的距離

[英]Calculating distance between two points using the distm function inside mutate

我正在嘗試計算兩組經度和緯度坐標之間的距離。

我正在使用來自封裝地理層的函數distm()來執行此操作。

如果我在distm()函數中手動輸入值,它會很好地工作,但是我無法在mutate命令中使用它。

在mutate函數中運行它時,出現錯誤:

Error in mutate_impl(.data, dots) : 
Evaluation error: Wrong length for a vector, should be 2.

@Dotpi在評論中寫道: “請注意,geosphere:distm方法未向量化。要對其向量化,請使用apply函數。” 當他在此線程中回復時(使用R計算兩點(緯度,經度)之間的地理空間距離的函數

據此,我猜測這是導致mutate函數錯誤的原因,但我不知道如何解決。 我希望使用tidyverse解決方案,但是可以提供任何幫助。

下面是一個測試數據框,其中首先包含產生錯誤的代碼,然后是一個工作示例,在該示例中,我手動從DF的第一行插入了值。

library(tidyverse)
library(geosphere)

set.seed(1)
DF <- tibble(
  Long1 = sample(1:10),
  Lat1 = sample(1:10),
  Long2 = sample(1:10),
  Lat2 = sample(1:10))

DF %>% mutate(
  Dist = distm(x= c(Long1, Lat1), y=c(Long2, Lat2), fun = distHaversine ))

distm( x = c(3, 3), y = c(10, 5), fun = distHaversine )

也許我們可以使用pmap

library(purrr)
pmap_dbl(DF, ~ distm(x = c(..1, ..2), y = c(..3, ..4), 
                    fun = distHaversine) %>% c)

mutate結合使用時

library(dplyr)
DF %>% 
  mutate(Dist = pmap_dbl(., ~
           distm(x = c(..1, ..2), y = c(..3, ..4), fun = distHaversine)))
# A tibble: 10 x 5
#   Long1  Lat1 Long2  Lat2     Dist
#   <int> <int> <int> <int>    <dbl>
# 1     3     3    10     5  808552.
# 2     4     2     2     6  497573.
# 3     5     6     6     4  248726.
# 4     7    10     1     2 1110668.
# 5     2     5     9    10  951974.
# 6     8     7     8     8  111319.
# 7     9     8     7     9  246730.
# 8     6     4     5     1  351986.
# 9    10     1     3     7 1024599.
#10     1     9     4     3  745867.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM