计算R中的加权多边形质心 [英] Calculating weighted polygon centroids in R

查看:109
本文介绍了计算R中的加权多边形质心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据单独的人口网格数据集计算一组空间区域的质心.感谢您为下面的示例提供指导.

I need to calculate the centroids of a set of spatial zones based on a separate population grid dataset. Grateful for a steer on how to achieve this for the example below.

谢谢.

require(raster)
require(spdep)
require(maptools)

dat <- raster(volcano)   # simulated population data
polys <- readShapePoly(system.file("etc/shapes/columbus.shp",package="spdep")[1])

# set consistent coordinate ref. systems and bounding boxes
proj4string(dat) <- proj4string(polys) <- CRS("+proj=longlat +datum=NAD27")
extent(dat) <- extent(polys)

# illustration plot
plot(dat, asp = TRUE)
plot(polys, add = TRUE)

推荐答案

三个步骤:

首先,找到每个多边形中的所有单元格,并返回一个包含单元格编号和值的2列矩阵的列表:

First, find all the cells in each polygon, return a list of 2-column matrices with the cell number and the value:

require(plyr) # for llply, laply in a bit...
cell_value = extract(dat, polys,cellnumbers=TRUE)
head(cell_value[[1]])
     cell value
[1,]   31   108
[2,]   32   108
[3,]   33   110
[4,]   92   110
[5,]   93   110
[6,]   94   111

第二,转到相似矩阵的列表,但添加x和y坐标:

Second, turn into a list of similar matrices but add the x and y coords:

cell_value_xy = llply(cell_value, function(x)cbind(x,xyFromCell(dat,x[,"cell"])))
head(cell_value_xy[[1]])
     cell value        x        y
[1,]   31   108 8.581164 14.71973
[2,]   32   108 8.669893 14.71973
[3,]   33   110 8.758623 14.71973
[4,]   92   110 8.581164 14.67428
[5,]   93   110 8.669893 14.67428
[6,]   94   111 8.758623 14.67428

第三,计算加权平均坐标.这忽略了任何边缘效果,并假设所有网格单元的大小相同:

Third, compute the weighted mean coordinate. This neglects any edge effects and assumes all grid cells are the same size:

centr = laply(cell_value_xy, function(m){c(weighted.mean(m[,3],m[,2]), weighted.mean(m[,4],m[,2]))})
head(centr)
            1        2
[1,] 8.816277 14.35309
[2,] 8.327463 14.02354
[3,] 8.993655 13.82518
[4,] 8.467312 13.71929
[5,] 9.011808 13.28719
[6,] 9.745000 13.47444

现在,centr是一个2列矩阵.在您的示例中,该示例非常接近coordinates(polys),因此我将创建一个人为设计的示例,并使用一些极端的权重以确保其按预期工作.

Now centr is a 2-column matrix. In your example its very close to coordinates(polys) so I'd make a contrived example with some extreme weights to make sure its working as expected.

这篇关于计算R中的加权多边形质心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆