简体   繁体   English

在 R 中使用 `mutate_at` 或 `map` 函数来计算多个位置之间的距离

[英]Using `mutate_at` or a `map` function in R to calculate distances between multiple locations

I have on dataframe ( controids ) with longitudes and latitudes for a set of locations:我在数据controidscontroids )上有一组位置的经度和纬度:

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) 

I have a second dataframe ( towns ) with longitudes and latitudes for a second set of places.我有第二个数据框( towns ),其中包含第二组地点的经度和纬度。

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

I want to add three columns to centroids giving the straight-line distance, in kilometers, between each city and each of the three towns in towns .我想三列添加到centroids给直线距离,以公里,每个城市和每个在三个镇之间towns So the final dataframe would look like this (distances not correct, just for illustration):所以最终的数据框看起来像这样(距离不正确,仅供说明):

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)

I have to do this for a large number of towns so I'm trying to write some code that's easy to generalize.我必须为大量城镇执行此操作,因此我正在尝试编写一些易于概括的代码。 Here is what I have so far.这是我到目前为止所拥有的。

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]) ))))

I want to know if there's a way to do this using mutate_at and/or a purrr map function - one that fills in the TOWN_dist column name automatically and inputs the correct row from the town dataframe.我想知道是否有办法使用mutate_at和/或purrr map函数来做到这一点 - 一个自动填充 TOWN_dist 列名并从town数据框中输入正确行的方法。

We can use map to loop over the 'towns'我们可以使用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))))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM