Crop a RasterLayer with a SpatialPolygonDataFrame

只谈情不闲聊 提交于 2019-12-04 21:15:29

Crop does not crop to the country polygons as you would think. In fact, the crop(grid, world) does not really crop anything, as the extent of world is larger than the extent of grid. You can check that by plotting test. It's just the same as grid.

Instead, after grid[] = runif(1:ncell(grid)) you could do:

# 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))

I believe that's what you're after.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!