r - 如何使用R计算点与参考点之间的距离?
问题描述
我有这个数据框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 进行编码以获得近似距离?
解决方案
您可以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")
推荐阅读
- mongodb - NestJS、MongoDB、Mongoose、GraphQL - 重复自己描述用户或任何模型
- ios - 多个应用程序用户访问 CloudKit 中的私有数据库
- unity3d - 使用 ScreenCapture.CaptureScreenshotAsTexture() 后如何显示纹理;
- javascript - 在段落之后插入元素(不仅仅是节点)
- javascript - 如何从 UWP WebView 中提取 httponly cookie?
- python-3.x - 为什么 tkinter 方面在 Windows 7 中不起作用?
- java - 从字符串慢慢将文本打印到 JLabel?
- tcl - 为什么 tcl 认为空字符串是双精度的?
- python-3.x - 如何在 QGridLayout 中为隐藏的 QtWaitingSpinner 保留空间?
- python - python tkinter 字体大小跨平台