簡體   English   中英

計算二維歐氏距離並將其添加為數據中的列

[英]Calculating two dimensions Euclidean distance and adding it as a column in the data

我需要創建一個變量來測量與 APP 的距離。 APP的中心在坐標1440000東,12160000北。 我需要創建一個新列來計算每個人與 APP (dist.APP) 中心之間的歐幾里德距離。

這是我到目前為止所擁有的,但我不確定該方程是否適用於二維:

east = "1440000"

north = "12160000"

b1 = east
b2 = north

dist.APP <- function(a1, b1, a2, b2) {sqrt((a1 - b1)^2 + (a2 - 
b2)^2)
  apply(datwolfcoy, FUN = dist.APP, MARGIN = 2)
  }

這是您指定 APP 坐標中心向量的方式嗎?

為了將其添加為每個人的一列,這並不完全有效,我認為它適用於所有列,而不僅僅是我指定的個人(邊距 = 2)。

我也試過這個,但沒有運氣:

dist.APP <- data.frame(function(a1, b1, a2, b2) {sqrt((a1 - b1)^2 + (a2 - b2)^2)
}

這是我的數據的樣子:

ID  PackNumber  StudyArea   CoyoteAncestry(Logit)   PrimaryRds  SecondaryRds    TertiaryRds  Deer   Moose   east    north
49-2    1   Out -0.834473518    0.088   0.499   0.015   0.087   0.112   1358690 12086700
49-3    2   Out -2.408854287    0   0.302   0.188   0   0.382   1346840 12099300
49-4    2   Out -3.896934876    0   0.5 0.164   0.057   0.385   1343380 12100000
49-7    2   Out -2.699548556    0   0.5 0.164   0.057   0.385   1343380 12100000

一個可能的解決方案:

df <- data.frame(
         stringsAsFactors = FALSE,
              check.names = FALSE,
                       ID = c("49-2", "49-3", "49-4", "49-7"),
               PackNumber = c(1L, 2L, 2L, 2L),
                StudyArea = c("Out", "Out", "Out", "Out"),
        `CoyoteAncestry(Logit)` = c(-0.834473518,-2.408854287,-3.896934876,
                                    -2.699548556),
               PrimaryRds = c(0.088, 0, 0, 0),
             SecondaryRds = c(0.499, 0.302, 0.5, 0.5),
              TertiaryRds = c(0.015, 0.188, 0.164, 0.164),
                     Deer = c(0.087, 0, 0.057, 0.057),
                    Moose = c(0.112, 0.382, 0.385, 0.385),
                     east = c(1358690L, 1346840L, 1343380L, 1343380L),
                    north = c(12086700L, 12099300L, 12100000L, 12100000L)
      )

euc.dist <- function(x)
{  
  sqrt((1440000-x[1])^2 + (12160000-x[2])^2)
}  
  
df <- cbind(df, dist = apply(df[,c("east", "north")],1, euc.dist))

#>     ID PackNumber StudyArea CoyoteAncestry(Logit) PrimaryRds SecondaryRds
#> 1 49-2          1       Out            -0.8344735      0.088        0.499
#> 2 49-3          2       Out            -2.4088543      0.000        0.302
#> 3 49-4          2       Out            -3.8969349      0.000        0.500
#> 4 49-7          2       Out            -2.6995486      0.000        0.500
#>   TertiaryRds  Deer Moose    east    north     dist
#> 1       0.015 0.087 0.112 1358690 12086700 109472.4
#> 2       0.188 0.000 0.382 1346840 12099300 111190.3
#> 3       0.164 0.057 0.385 1343380 12100000 113734.0
#> 4       0.164 0.057 0.385 1343380 12100000 113734.0

暫無
暫無

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

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