r - 如何按组计算平均空间位置
问题描述
我需要计算具有经度和纬度变量的空间数据的平均位置。操作需要分组进行,这使事情有些复杂。对于简单的加权平均值(下面的示例),我已经能够做到这一点,但是更复杂的度量并不容易实现。
示例数据:
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
. 关于如何有效实现这一目标的任何建议?
解决方案
一种方法是按组嵌套数据,然后用于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)
推荐阅读
- vba - 带有 RC 表示法和 vlookup 的 activecell.formula 无法正常工作 vba
- amazon-web-services - AWS API GATEWAY 配置从 lambda 返回二进制 pdf 文件
- php - 无法为新的自定义帖子类型注册分类
- node.js - 从本地应用程序以快递方式接收 webhook
- python - 将列表从海量字典转换为数据框的问题
- python - 清除事件不会停止其他线程
- automated-tests - 自动化浏览器测试的简短通用术语是什么?
- c# - 如何列出已安装的 OPOS 生物识别设备?
- javascript - 使用数据属性将鼠标悬停在链接上时更改(和淡入/淡出)图像
- mongodb - Meteor 让一个用户阅读和更新所有文档