【问题标题】:Find two points farthest apart using group_by() in Sf使用 Sf 中的 group_by() 找到相距最远的两个点
【发布时间】:2020-08-17 11:05:55
【问题描述】:

虽然有几个相关的,但无法找到准确的 Q/A 来解决这个问题。我试图为 ID 列定义的所有点组计算距离矩阵。然后选择离每组最远的两个点,保留原来的组id。每组的点数从 2、4 或 6 不等。

我的科幻小说:

    df <- data.frame(x = runif(12), y = runif(12), id = rep(1:3,each = 4)) %>% 
      st_as_sf(coords = c("x","y"), crs = 27700)

我试过这样的代码:

a <- df %>% 
      group_by(id) %>% 
      st_distance(.)

虽然这只是返回所有点的距离矩阵。

下面给出了我想要的,尽管我担心它在大型数据集上会很慢:

  maxMin <- do.call(rbind,lapply(unique(allInts$id), function(x) {
      df <- allInts %>% filter(id == x)
      d <- st_distance(df)
      df %>% slice(unique(as.vector(which(d == max(d),arr.ind=T))))
    }))

【问题讨论】:

    标签: r gis sf


    【解决方案1】:

    您可以使用dplyr::group_split 将数据框拆分为每个组的列表。然后,您可以使用 map/lapply 将您想要的任何功能应用于该列表。

    下面的脚本保留了每组中相距最远的 2 个点。

    library(sf)
    library(tidyverse)
    
    # dummy data
    data <- data.frame(x = runif(12), y = runif(12), id = rep(1:3,each = 4)) %>% 
    st_as_sf(coords = c("x","y"), crs = 27700)
    
    # split it into a list per ID
    data_group <- data %>% 
    group_by(id) %>%
    group_split()
    
    #apply a function to each list
    distance_per_group <- map(data_group, function(x){
    distance_matrix <- st_distance(x)
    biggest_distance <- as.numeric(which(distance_matrix == max(distance_matrix), arr.ind = TRUE)[1,])
    farthest_apart <- x[biggest_distance,]
    })
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    相关资源
    最近更新 更多