具有多个多边形的形状文件,其具有区域和图形的逻辑划分。地块重叠在区域上。任务是解析/合并带有区域的图,没有重叠。
这是形状文件的spplot。这里的地块位于Field Zones的顶部。这里也是具有重叠多边形(区域和图形)的shapefile:Shapefile
在QGIS中,使用提取区域和图解,找到差异然后使用Union解析也是如此。现在需要在R中编程相同。
尝试在R中的步骤下面但是无法获得正确的结果,寻找如何在R中解散这种类型的重叠ploygons的方法:
library(sp);
library(raster);
library(rgeos)
#Importing the shape files
field_boundary_fp <- "Database/gadenstedt2_outer_field 3 -26_0_zoned-plotm.shp"
poly_map_proj_str <- "+proj=longlat +datum=WGS84 +no_defs";
utm_target_proj <- "+init=epsg:32632";
field_boundary_sdf <- maptools::readShapePoly(fn = field_boundary_fp,
proj4string = CRS(poly_map_proj_str),
repair = T,
delete_null_obj = T,
verbose = T);
spplot(
field_boundary_sdf,"Rx"
)
# Extracting the Zones and Plots#
Zone_sdf <- field_boundary_sdf[field_boundary_sdf@data$Type == "Zone", ]
Plot_sdf <- field_boundary_sdf[field_boundary_sdf@data$Type == "Plot", ]
plot(Plot_sdf)
plot(Zone_sdf)
#Finding the Intersection Part between the both
test <- gIntersection(Zone_sdf, Plot_sdf,id="ZoneIdx")
plot(test)
plot(test, add = T, col = 'blue')
# Finding the difference
test2 <- gDifference(Zone_sdf,Plot_sdf,id="ZoneIdx")
plot(test2)
plot(test2, add = T, col = 'red')
#Trying for Union then
polygon3 <- gUnion(test2, Plot_sdf,id="ZoneIdx")
plot(polygon3)
plot(polygon3, add = T, col = 'yellow')
阅读shapefile
library(raster)
fields <- shapefile("gadenstedt2_outer_field 3 -26_0_zoned-plotm.shp")
首先分开区域和字段。
zone <- fields[fields$Type == "Zone", ]
plot <- fields[fields$Type == "Plot", ]
删除区域中的绘图
d <- erase(zone, plot)
然后将plot
附加到d
r <- bind(plot, d)
现在聚合
rd <- aggregate(r, "Rx")
spplot(rd, "Rx")
----现在有一个可重复的例子,以便其他人也可以受益;你不应该提出依赖于需要下载的文件的问题----
示例数据(两个SpatialPolygonDataFrame对象)
library(raster)
p <- shapefile(system.file("external/lux.shp", package="raster"))
p <- aggregate(p, "NAME_1")
p$zone <- 10 + (1:length(p))
r <- raster(ncol=2, nrow=2, vals=1:4, ext=extent(6, 6.4, 49.75, 50), crs=crs(p))
names(r) <- "zone"
b <- as(r, 'SpatialPolygonsDataFrame')
擦除并附加
e <- erase(p, b)
pb <- bind(e, b)
data.frame(pb)
# NAME_1 zone
#1 Diekirch 11
#2 Grevenmacher 12
#3 Luxembourg 13
#4 <NA> 1
#5 <NA> 2
#6 <NA> 3
#7 <NA> 4
要确保解决方案适用于所有字段,请在上面的解决方案中添加额外的代码行以添加缓冲区几何。
fields <- gBuffer(fields, byid=TRUE, width=0) # Expands the given geometry to include
the area within the specified width
zone <- fields[fields$Type == "Zone", ]
plot <- fields[fields$Type == "Plot", ]
d <- erase(zone, plot)
spplot(d, "Rx")
r <- bind(plot, d)
rd <- aggregate(r, "Rx")
spplot(rd, "Rx")