1

I have raster data for whole world (filename.bil) and a Shapefile (filename.shp) for USA. How to draw map for USA by using the raster data (filename.bil) in R plot?

shape <- shapefile(file.path(gadmdir,"gadm36_USA_1.shp”))
b <- brick(file.path(gaezdir, "plate47.bil"))
r <- raster(shape, res=0.0833333 )
values(r) <- 1:ncell(r)
cropextent <- mask(r, shape)

plot(cropextent)
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
mho
  • 53
  • 1
  • 8

2 Answers2

1

Here's an example that makes raster and shape data and extracts the raster values from the extent of the shape. It's a modification of the help text for the raster::crop function.

library(raster)
library(sp)
r <- raster(nrow=450, ncol=900)
values(r) <- 1:ncell(r)

# crop Raster* with Spatial* object
b <- as(extent(0, 10, 40, 50), 'SpatialPolygons')
crs(b) <- crs(r)
rb <- crop(r, b)

plot(r)
plot(b, add=T)

enter image description here

plot(rb)

enter image description here

Andrew Chisholm
  • 6,362
  • 2
  • 22
  • 41
  • This won’t work in my case. Because it won’t give the shape of the country. This command will just crop the raster in rectangular form. – mho Apr 21 '20 at 21:19
1

You can use crop followed by mask

Example data

library(raster)
r <- raster()
values(r) <- 1:ncell(r)
p <- getData("GADM", country="Mexico", level=1)

Solution

x <- crop(r, p)
y <- mask(x, p)

Have a look

#original 
plot(r)
lines(p)

# processed
plot(y)
lines(p)
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63