R 中是否有一种巧妙的方法来获得加权地理质心?

Is there a neat way in R to get a weighted geographical centroid?

我知道 rgeos 包中的 gCentroid 函数给出了一组经度、纬度点的地理质心...但是如果我想为这些点分配权重,我该如何找到加权质心?

例如,假设我想找到最好的聚会地点...我有 10 人在伦敦,2 人在利兹,5 人在格拉斯哥。我如何找到组合努力最少的地方?

您可以创建一个空间对象,其中每个点代表一个人,然后伦敦 10 分,利兹 2 分,格拉斯哥 5 分。 gCentroid 函数将适当地加权。

这是一个例子。

library(dplyr)
library(rgeos)
library(sp)

# Locations of cities
city_locations <- tibble(  
    Name = c("London", "Glasgow", "Leeds"),
    lat = c(51.507222, 55.860916, 53.799722),
    lon = c(-0.1275,-4.251433,-1.549167)
)
# More elegant way to repeat cities
people_counts <- c(rep('London', 10), rep('Glasgow', 5), rep('Leeds', 2))

# Code to join repeated cities with lat and lon
people <- 
    tibble(Name=people_counts) %>% 
    left_join(city_locations, by='Name') 

# make a spatial points data frame
people_sp <- SpatialPointsDataFrame(people, coords = people[c('lon', 'lat')], proj4string = CRS('EPSG:4326'))

# find the centroid
pub <- gCentroid(people_sp)
pub$Name <- 'Centroid'

library(mapview)
# plot on a map
mapview(people_sp) + mapview(pub, col.regions='red')

看起来像是德比以北的某个地方。