裁剪SpatialPolygonsDataFrame

Jia*_*ang 27 r crop spatial

我有两个SpatialPolygonsDataFrame文件:dat1,dat2

extent(dat1)
class       : Extent 
xmin        : -180 
xmax        : 180 
ymin        : -90 
ymax        : 90 


extent(dat2)
class       : Extent 
xmin        : -120.0014 
xmax        : -109.9997 
ymin        : 48.99944 
ymax        : 60 
Run Code Online (Sandbox Code Playgroud)

我想使用dat2的范围裁剪文件dat1.我不知道怎么做.我之前只使用"crop"函数处理光栅文件.

当我将此函数用于当前数据时,会发生以下错误:

> r1 <- crop(BiomassCarbon.shp,alberta.shp)
Error in function (classes, fdef, mtable)  : 

 unable to find an inherited method for function ‘crop’ for signature"SpatialPolygonsDataFrame"’
Run Code Online (Sandbox Code Playgroud)

Jos*_*ien 56

精简方法新增2014-10-9:

raster::crop()可用于裁剪Spatial*(以及Raster*)对象.

例如,以下是如何使用它来裁剪SpatialPolygons*对象:

## Load raster package and an example SpatialPolygonsDataFrame
library(raster) 
data("wrld_simpl", package="maptools")

## Crop to the desired extent, then plot
out <- crop(wrld_simpl, extent(130, 180, 40, 70))
plot(out, col="khaki", bg="azure2")
Run Code Online (Sandbox Code Playgroud)

原始(仍然功能)答案:

该rgeos功能gIntersection()使这个非常简单.

使用mnel的漂亮示例作为跳跃点:

library(maptools)
library(raster)   ## To convert an "Extent" object to a "SpatialPolygons" object.
library(rgeos)
data(wrld_simpl)

## Create the clipping polygon
CP <- as(extent(130, 180, 40, 70), "SpatialPolygons")
proj4string(CP) <- CRS(proj4string(wrld_simpl))

## Clip the map
out <- gIntersection(wrld_simpl, CP, byid=TRUE)

## Plot the output
plot(out, col="khaki", bg="azure2")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


mne*_*nel 5

以下是rgeos使用世界地图作为示例的示例

这来自Roger Bivand的R-sig-Geo邮件列表.罗杰是该sp方案的作者之一.

以世界地图为例

library(maptools)

data(wrld_simpl)

# interested in the arealy bounded by the following rectangle
# rect(130, 40, 180, 70)

library(rgeos)
# create  a polygon that defines the boundary
bnds <- cbind(x=c(130, 130, 180, 180, 130), y=c(40, 70, 70, 40, 40))
# convert to a spatial polygons object with the same CRS
SP <- SpatialPolygons(list(Polygons(list(Polygon(bnds)), "1")),
proj4string=CRS(proj4string(wrld_simpl)))
# find the intersection with the original SPDF
gI <- gIntersects(wrld_simpl, SP, byid=TRUE)
# create the new spatial polygons object.
out <- vector(mode="list", length=length(which(gI)))
ii <- 1
for (i in seq(along=gI)) if (gI[i]) {
  out[[ii]] <- gIntersection(wrld_simpl[i,], SP)
  row.names(out[[ii]]) <- row.names(wrld_simpl)[i]; ii <- ii+1
}
# use rbind.SpatialPolygons method to combine into a new object.
out1 <- do.call("rbind", out)
# look here is Eastern Russia and a bit of Japan and China.
plot(out1, col = "khaki", bg = "azure2")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述