Overlay shapefile and rasterlayer in R?

2020-05-06 11:05发布

问题:

I have a raster layer with climate data from the north of Mexico, part of Canada and the US mainland. I am trying to restrict the climate data to only the zone of the US mainland. To do this I thought it would be easy to import a US mainland map and overlay it with my raster data (of course this is turning out to be a lot more difficult than I thought). So far, using the rgdal library, I have managed to import a shapefile including the USA mainland map with states divisions. Now I want to convert this into a raster layer so that can finally overlay it with my initial climate raster layer. This is the code that I am using:

setwd ("C:/Climate_data/USA map")
ogrInfo(".", "USA_mainland_states")
usa_state = readOGR(dsn=".", layer="USA_mainland_states")

##Convert to Raster 
r_usa_state <- raster()
extent(r_usa_state) <- extent(usa_state)
rasterize(usa_state,r_usa_state, fun='last')
overlay (r_usa_state, sms_av, fun='mask')

However, now I get the following error:

Error in .readCells(x, cells, 1) : no data on disk or in memory

sms_av is the climate rasterlayer (103936 elements, 823.3 kb).

Also, when I do:

hasValues(r_usa_state)

I get:

FALSE

What am I doing wrong?? Any advice would be GREATLY appreciated!!!!