使用SpatialPolygonsDataFrame裁剪栅格图层

时间:2014-05-23 10:36:57

标签: r r-raster spatial-data-frame

我有一个栅格网格,我想根据包'maptools'数据提供的世界地图的地面边界进行裁剪。通过做一些研究,我发现我必须使用crop()函数,然后使用mask()函数,但是我收到一条错误消息。

这是我的代码:

# load the worldmap SpatialPolygonDataFrame
library(maptools)
data(wrld_simpl)
ll=CRS("+init=epsg:4326")
world<-spTransform(wrld_simpl, ll)
ext<-extent(-10.417,31.917,34.083,71.083)
# get only region covering europe 
world@bbox<-as.matrix(ext)


# create the origin in WGS84 CRS
ll = CRS("+init=epsg:4326") 
origin = SpatialPoints(cbind(7,40),ll) 
# create the raster grid 
grid = raster() 
# define extent and resolution
e = extent(5,18,40,50)
extent(grid)<-e
res(grid)=c(0.08,0.08) 
# fill the raster values
grid[] = runif(1:20250)

# crop the grid with worldmap to erase sea areas
test<-crop(grid,world)
rasterize(world,test)
Found 246 region(s) and 3768 polygon(s)
Error in if (x1a > rxmx) { : argument is of length zero

1 个答案:

答案 0 :(得分:0)

裁剪不会像您想象的那样裁剪到国家多边形。事实上,crop(grid, world)并没有真正收获任何东西,因为世界的范围大于网格的范围。您可以通过绘制test来检查。它与grid一样。

相反,在grid[] = runif(1:ncell(grid))之后你可以做到:

# we're going to make 3 plots
par(mfrow=c(1,3))

# crop the Worldmap to grid 
worldcrop<-crop(world, grid)
plot(worldcrop)

# rasterize output, give cells value of NAME(seas are NA)
worldcropr = rasterize(worldcrop,grid, field='NAME', fun='first')
plot(worldcropr)

# mask random grid by worldcropr
gridmask = mask(x=grid, mask=worldcropr)
plot(gridmask)

# number of land pixels:
sum(!is.na(gridmask@data@values))

# number of sea pixels:
sum(is.na(gridmask@data@values))

我相信这就是你所追求的。 cropped grid