【发布时间】: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_wider,newdf <- full_join(centroids, towns, by = character())转置,每次比较都会给你一行跨度>
标签: r dplyr tidyverse purrr sf