简体   繁体   中英

How to merge features contained in a shapefile based on a condition in R

I have attached a shapefile ( sample ) with 4 features and each of them have gap , out , in in the field type (Refer to the attribute table). I would like to merge feature gap feature with the adjacent polygon which has the maximum area (In this case the gap would be merged with in ). My final shapefile would have 3 features (without gap ). How do I do this in R?

In ArcGIS, there is a direct tool to merge feature. I wanted to know how we do this in R.

Here is the link to the shapefile 这是一个示例 shapefile,其中有 4 个特征

这是相应 shapefile 的图例

这是 shapefile 的属性表

I have used rgeos library to figure out the adjacent polygon with the maximum area. This is my code. I can't figure out how to merge this feature with the gap feature.

library(rgeos)
adj_mat <- gTouches(shp, byid=TRUE)
a <- adj_mat[which(shp@data$type=="gap"),]
area <- shp@data$SHAPE_Area[which(a=="TRUE")]
final_matching_id <- which(area==max(area))
f_gap <- shp@data[final_matching_id+1,]
f_gap

  OBJECTID SHAPE_Leng SHAPE_Area type
3       13   1.527046 0.09469124   in

gUnion and spRbind maybe solve your problem.

merged_d <- gUnion(shp[which(shp@data$type=="gap"),], shp[final_matching_id+1,])
not_related_d <- shp[c(1:4)[-c(which(shp@data$type=="gap"), final_matching_id+1)],]

shp2 <- spRbind(merged_d, not_related_d)

plot(shp2, col = 2:4)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM