首页 > 解决方案 > 如何按组计算平均空间位置

问题描述

我需要计算具有经度和纬度变量的空间数据的平均位置。操作需要分组进行,这使事情有些复杂。对于简单的加权平均值(下面的示例),我已经能够做到这一点,但是更复杂的度量并不容易实现。

示例数据:

df <- data.frame(longitude = c(22, 23, 24, 25, 26, 27),
                 latitude = c(56, 57, 58, 59, 60, 61),
                 weight = c(1, 2, 3, 1, 2, 3),
                 group = c("A", "A", "A", "B", "B", "B"))

简单加权平均值:

dfMean <- df %>%
      group_by(group) %>%
      summarize_at(vars(longitude, latitude), list(~weighted.mean(., weight))) %>%
      ungroup

我想用一个函数来计算这个geopshere::geomean。问题是该函数的输出是一个两列矩阵,与dplyr::summarize. 关于如何有效实现这一目标的任何建议?

标签: rdplyrgeospatial

解决方案


一种方法是按组嵌套数据,然后用于map()迭代分组数据。

library(geosphere)
library(tidyverse)

df %>% 
  nest(-group) %>%
  mutate(gmean = map(data, ~data.frame(geomean(xy = cbind(.x$longitude, .x$latitude), w = .x$weight)))) %>%
  unnest(gmean)

# A tibble: 2 x 4
  group data                 x     y
  <fct> <list>           <dbl> <dbl>
1 A     <tibble [3 x 3]>  23.3  57.3
2 B     <tibble [3 x 3]>  26.3  60.3

或使用相同的东西summarise

df %>%
  group_by(group) %>%
  summarise(gmean = list(data.frame(geomean(cbind(longitude, latitude), w = weight)))) %>%
  unnest(gmean)

推荐阅读