【问题标题】:How to calculate mean spatial location by group如何按组计算平均空间位置
【发布时间】:2019-06-10 07:37:56
【问题描述】:

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

示例数据:

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不兼容。有关如何有效实现这一目标的任何建议?

【问题讨论】:

  • as.tbl 包装一下吧?

标签: r dplyr geospatial


【解决方案1】:

一种方法是按组嵌套数据,然后使用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)

【讨论】:

    【解决方案2】:

    一种选择是将geomean 的值转换为逗号分隔的字符串,然后将separate 转换为不同的列。

    library(dplyr)
    library(tidyr)
    library(geosphere)
    
    df %>%
      group_by(group) %>%
      summarise(val = toString(geomean(cbind(longitude, latitude), weight))) %>%
      separate(val, c("cord1", "cord2"), sep = ",") %>%
      mutate_at(2:3, as.numeric)
    
    # A tibble: 2 x 3
    #    group cord1 cord2
    #    <fct> <dbl> <dbl>
    #1   A      23.3  57.3
    #2   B      26.3  60.3
    

    【讨论】:

    • 这是microbenchmark 最快的解决方案。其他的也是有效的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多