计算二维欧氏距离并将其添加为数据中的一列

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 坐标中心向量的方式吗?

为了将它添加为每个人的列,这不太奏效,我认为它适用于所有列,而不仅仅是个人,因为我指定了 (margin = 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