我正在寻找一种方法来计算列表空间多边形中每个多边形的重心:
我以为用了一个循环,但他让我为第一个多边形,我不知道的方式,我是R的新手,有人可以帮助我代码:
for ( i in 1:length(polys1_T)) {
xx=mean(coordinates(polys1_T[[i]])[,1])
yy=mean(coordinates(polys1_T[[i]])[,2])
aa<-as.data.frame(cbind(xx,yy))
}
Run Code Online (Sandbox Code Playgroud)
编辑:
码:
inter1 <- read.table("c:/inter1.csv", header=TRUE)
# add a category (required for later rasterizing/polygonizing)
inter1 <- cbind(inter1,
cat
= rep(1L, nrow(inter1)), stringsAsFactors = FALSE)
# convert to spatial points
coordinates(inter1) <- ~long + lat
# gridify your set of points
gridded(inter1) <- TRUE
# convert to raster
r <- raster(inter1)
# convert raster to polygons
sp <- rasterToPolygons(r, dissolve = T)
plot(sp)
# addition transformation to distinguish well the set of polygons
polys <- slot(sp@polygons[[1]], "Polygons")
# plot
plot(sp, border = "gray", lwd = 2) # polygonize result
Run Code Online (Sandbox Code Playgroud)
inter1.csv 结果:

多边形是9个多边形的列表:是否可以计算每个多边形的重心?
给rgeos::gCentroid看看.您可以通过多种方式应用它.如果你有一个SpatialPolygons对象,比如说,来自一个调用readOGR,你可以这样做:
map <- readOGR(dsn, layer)
centers <- data.frame(gCentroid(map, byid=TRUE))
Run Code Online (Sandbox Code Playgroud)
从它获得所有的质心.
顺便说一下:虽然准确 - 一个更常见的术语是"几何中心"/"质心"与"重心"
编辑
对于普通的,ol Polygon("硬"方式,但稍微更精确):
library(rgdal)
library(sp)
library(PBSmapping)
library(maptools)
do.call("rbind", lapply(polys, function(x) {
calcCentroid(SpatialPolygons2PolySet(SpatialPolygons(list(Polygons(list(x), ID=1)))))
}))[,3:4]
## X Y
## 1 5.8108434 20.16466
## 2 -3.2619048 29.38095
## 3 5.5600000 34.72000
## 4 3.8000000 32.57037
## 5 6.3608108 32.49189
## 6 -2.2500000 31.60000
## 7 -8.1733333 27.61333
## 8 0.3082011 27.44444
## 9 8.6685714 26.78286
Run Code Online (Sandbox Code Playgroud)
并且,使用几乎等效的手工方法:
do.call("rbind", lapply(polys, function(x) {
data.frame(mean(coordinates(x)[,1]), mean(coordinates(x)[,2]))
}))
## mean.coordinates.x....1.. mean.coordinates.x....2..
## 1 5.819892 20.15484
## 2 -3.242593 29.37778
## 3 5.539474 34.71579
## 4 3.815517 32.56552
## 5 6.323034 32.47191
## 6 -2.230952 31.60000
## 7 -8.140476 27.61905
## 8 0.350000 27.40885
## 9 8.746825 26.92063
Run Code Online (Sandbox Code Playgroud)
每种方法都为每个列表元素提供了质心(在您提供的示例中有9个而不是5个).
如果您有大量的这些,请考虑rbindlist从data.table包中使用(更快速+更高效的内存).
| 归档时间: |
|
| 查看次数: |
1597 次 |
| 最近记录: |