【问题标题】:Counting polygons in shapefile计算 shapefile 中的多边形
【发布时间】:2013-04-19 19:29:15
【问题描述】:

所以我有多个物种范围,如下所示(例如蓝色)这个范围从东到西横跨非洲:

我可以通过在rgeos 包中使用gArea 来获得总面积。我想知道的是这个文件有多少个单独的多边形 - 即总范围中有多少不同的区域(这可能是岛屿,或者只是分离的人口)以及 这些多边形的范围是。我一直在使用以下代码:

#Load example shapefile
shp <- readShapeSpatial("species1.shp")

#How many polygon slots are there?
length(shp@polygons)

>2

#How many polygons are in each slot
length(shp@polygons[[1]]@Polygons
length(shp@polygons[[2]]@Polygons

并获取特定区域的面积:

shp@polygons[[1]]@Polygons[[1]]@area

这是正确的吗?我担心范围中间的一个湖可能会自己构成一个多边形?我想最终得到一个大致如下的列表:

           Species A    Species B
Polygon 1      12          11
Polygon 2      13          10
Polygon 2      14          NA

如果我想为每个物种编译一个列表,说明有多少个多边形及其各自的范围,如果上面的代码是正确的,那么传递给一个循环将非常简单。

谢谢

【问题讨论】:

  • 你要数洞(湖和类似的洞)吗?
  • 不,我不想要湖
  • 应该是多边形中的一个洞,即它不能单独存在,但这取决于你所拥有的 shapefile 的质量。您可以尝试运行unlist( sapply( sapply( shp@polygons, slot , "Polygons" ) ,function(x) sapply(x , slot , "hole" ) ) ) 以查看是否有任何多边形被归类为孔?孔是多边形的一部分,gArea 将减去多边形内孔的面积来计算面积。
  • 是的,有些确实被归类为漏洞

标签: r extract polygon area shapefile


【解决方案1】:

这是一个非常平淡无奇的解决方案,但它现在可以完成工作。

for(i in 1:length(shpfiles)){

shp <- shpfiles[[i]]

#1) Create master list of all polygon files within a shapefile

#How many lists of polygons are there within the shpfile
num.polygon.lists <- length(shp@polygons)


#Get all polygon files
master <- vector(mode="list")
for(i in 1:num.polygon.lists){
m <- shp@polygons[[i]]@Polygons

master[[i]] <- m
}

#Combine polygon files into a single list
len <- length(master)

if(len > 1) {

root <- master[[1]]
for(i in 2:length(master)){
root <- c(master[[i]], root)}

} else {root <- master[[1]]}

#Rename
polygon.files <- root

#2) Count number of polygon files that are not holes

#Create a matrix for the total number of polygon slots that are going to be counted
res <- matrix(NA,ncol=1 , nrow=length(polygon.files))

#Loop through polygons returning whether slot "hole" is TRUE/FALSE
for(i in 1:length(polygon.files)){

r <- isTRUE(polygon.files[[i]]@hole)

res[[i,1]] <- r
}

#Count number times "FALSE" appears - means polygon is not a hole
p.count <- table(res)["FALSE"]
p.count <- as.numeric(p.count)

print(p.count)

}

这是一个开始

【讨论】:

    【解决方案2】:

    我使用以下代码找出 shapefile 的每一“行”中有多少个多部分多边形...

    sapply(shapefile@polygons, 函数(p) 长度(p@Polygons))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-26
      • 2022-01-11
      • 2014-01-30
      • 1970-01-01
      • 2021-11-03
      • 1970-01-01
      • 2022-07-06
      • 2015-08-29
      相关资源
      最近更新 更多