【问题标题】:Using `mutate_at` or a `map` function in R to calculate distances between multiple locations在 R 中使用 `mutate_at` 或 `map` 函数来计算多个位置之间的距离
【发布时间】:2021-01-01 11:38:28
【问题描述】:

我有一组位置的经度和纬度数据框 (controids):

library(tidyverse)

centroids <- 
  tribble(
    ~city, ~long, ~lat, 
    "A", -89.92702, 44.19367, 
    "B", -89.92525, 44.19654,
    "C", -89.92365, 44.19756, 
    "D", -89.91949, 44.19848, 
    "E", -89.91359, 44.19818) 

我有第二个数据框 (towns),其中包含第二组地点的经度和纬度。

towns <- 
  tribble(
    ~town, ~long, ~lat,
    "greentown", -89.92225, 44.19727,
    "bluetown", -89.92997, 44.19899,
    "redtown", -89.91500, 44.19600)

我想在centroids 中添加三列,给出towns 中每个城市和三个城镇之间的直线距离(以公里为单位)。所以最终的数据框看起来像这样(距离不正确,仅用于说明):

output <- 
  tribble(
    ~city, ~long, ~lat, ~greentown_dist, ~bluetown_dist, ~redtown_dist,
    "A", -89.92702, 44.19367, 5.3, 2.0, 1.2,
    "B", -89.92525, 44.19654, 4.4, 2.3, 9.9,
    "C", -89.92365, 44.19756, 3.7, 5.4, 3.3,
    "D", -89.91949, 44.19848, 2.6, 3.9, 6.7,
    "E", -89.91359, 44.19818, 10.2, 2.2, 3.1)

我必须为大量城镇执行此操作,因此我正在尝试编写一些易于概括的代码。这是我目前所拥有的。

library(sf)

towns <- towns %>% st_as_sf(., coords=c('long', 'lat')) %>% st_geometry()

output <- 
  centroids %>% 
  st_as_sf(., coords=c('long', 'lat')) %>% 
  mutate(greentown_dist = st_distance(geometry, st_point(c( unlist(towns[1]) ))), 
         bluetown_dist = st_distance(geometry, st_point(c( unlist(towns[2]) ))), 
         redtown_dist = st_distance(geometry, st_point(c( unlist(towns[3]) ))))

我想知道是否有办法使用 mutate_at 和/或 purrr map 函数来执行此操作 - 自动填写 TOWN_dist 列名并从 town 数据框中输入正确的行.

【问题讨论】:

  • 我认为实现你想要的东西的一种方法是做一个full_join(),然后做你的计算,然后用pivot_widernewdf &lt;- full_join(centroids, towns, by = character())转置,每次比较都会给你一行跨度>

标签: r dplyr tidyverse purrr sf


【解决方案1】:

我们可以使用map 循环遍历“城镇”

centroids[paste0(c("green", "blue", "red"), "town_dist")] <- map(towns,
       ~ centroids %>% 
            st_as_sf(., coords = c('long', 'lat')) %>%
            transmute(dist = st_distance(geometry, st_point(c( unlist(.x))))))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 2020-01-28
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多