如何使用R计算参考点与参考点之间的距离?

时间:2020-02-09 21:35:01

标签: r coordinates distance

我有这个数据帧individual_dets,其中有一些经度和纬度值。这是数据框

individual_dets = structure(list(location = c("ARB-04", "BIRCHY HEAD", "Boca1", 
"BON-AR-S2", "BON-AR-S2", "BON-W-S5"), month = structure(c(12L, 
10L, 10L, 8L, 11L, 2L), .Label = c("Jan", "Feb", "Mar", "Apr", 
"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = c("ordered", 
"factor")), year = c(2018, 2018, 2018, 2018, 2018, 2018), detection_count = c(3L, 
256L, 2L, 4L, 2L, 2L), num_unique_tags = c(1L, 1L, 1L, 1L, 1L, 
1L), total_res_time_in_seconds = c(0, 1182040, 0, 2732221, 0, 
0), latitude = c(24.94808, 44.5713, 26.32559, -49.27732, -49.27732, 
-49.27985), longitude = c(-80.45412, -64.03512, -80.07108, 69.48038, 
69.48038, 69.47853)), class = c("grouped_df", "tbl_df", "tbl", 
"data.frame"), row.names = c(NA, -6L), groups = structure(list(
    location = c("ARB-04", "BIRCHY HEAD", "Boca1", "BON-AR-S2", 
    "BON-AR-S2", "BON-W-S5"), month = structure(c(12L, 10L, 10L, 
    8L, 11L, 2L), .Label = c("Jan", "Feb", "Mar", "Apr", "May", 
    "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = c("ordered", 
    "factor")), .rows = list(1L, 2L, 3L, 4L, 5L, 6L)), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"), .drop = TRUE))

但是,我的数据框有4247个观察值。

纬度和经度值用于表示西北大西洋中整个海洋的坐标。我正在尝试计算这些经度和纬度值与哈利法克斯的距离。

有人告诉我先使用此功能snap points to line,然后再使用lappy,但我正在查看结构,我非常迷失。有人知道如何使用函数snap points to line和lappy进行编码以获得近似距离吗?

1 个答案:

答案 0 :(得分:3)

您可以从st_distance()包中使用sf

library(sf)
library(dplyr)

individual_dets_sf <- st_as_sf(individual_dets, coords = c("longitude", "latitude"),
                               crs = 4326) %>% 
  ungroup()
halifax <- data.frame("longitude" = -63.5752, "latitude" = 44.6488)
halifax_sf <- st_as_sf(halifax, 
                       coords = c("longitude", "latitude"),
                       crs = 4326,
                       remove = FALSE) 

individual_dets_sf_2 <- individual_dets_sf %>% 
  mutate(distances = st_distance(., halifax_sf, by_element = TRUE))

individual_dets_sf_2$distances

Units: [m]
[1]  2664402.84    37510.33  2513963.08 16466708.65 16466708.65 16466623.17

如果您想将其可视化(蓝色的哈利法克斯):

library(tmap)

tmap_mode("view")

tm_shape(individual_dets_sf_2 %>% mutate(distances = units::drop_units(distances))) + tm_dots(col = "distances") +
  tm_shape(halifax_sf) + tm_dots(col = "blue")

enter image description here

相关问题