简体   繁体   English

使用sf按组到最近点的距离

[英]Distance to nearest point by group using sf

I have a dataset that looks similar to the example below. 我有一个看起来与下面的示例相似的数据集。 For each code I would like to calculate the distance to the next nearest code that belongs to the same area as it. 对于每个code我想计算到与它属于同一area的下一个最近代码的距离。 So in my example, for each code belonging to area A001 I would be after an additional column in the dataset that contains the minimum distance to one of the other points that belong to area A001. 因此,在我的示例中,对于属于区域A001的每个代码,我将在数据集中的另一列之后,该列包含与属于区域A001的其他点之一的最小距离。 I assume there should be a way of using st_distance to achieve this? 我认为应该有一种使用st_distance来实现这一目标?

require("data.table")
require("sf")

dt1 <- data.table(
code=c("A00111", "A00112","A00113","A00211","A00212","A00213","A00214","A00311","A00312"),
area=c("A001", "A001","A001","A002","A002","A002","A002","A003","A003"),
x=c(325147,323095,596020,257409,241206,248371,261076,595218,596678),
y=c(286151,284740,335814,079727,084266,078283,062045,333889,337836))

sf1 <- st_as_sf(dt1, coords = c("x","y"), crs=27700, na.fail=FALSE)

There might be a 'cleaner' way to get here, but this gets you the correct values. 到达这里可能会有一种“更清洁”的方法,但这可以为您提供正确的值。

library(tidyverse)

# intermediate fun to help later in apply()
smallest_non_zero <- function(x) {
  min_val <- min(x[x != 0])
  x[match(min_val, x)]
}

closest_grp_distances <- sf1 %>%
  group_split(area) %>%
  map(~st_distance(., .) %>% # returns matrix
       apply(1, smallest_non_zero)) %>%
  unlist()

sf1$closest_grp_distances <- closest_grp_distances

I wanted to use the baseR split but it doesn't have a method for sf objects. 我想使用baseR split但是它没有用于sf对象的方法。

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

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