[GIS] Set the minimum and maximum values for an elevation raster in R

elevationrrasterrgdalsp

I have a raster that displays elevational values at a global scale. I would like to set the minimum and maximum values based on the values I would like to choose.

> elev
class       : RasterLayer 
dimensions  : 18000, 43200, 777600000  (nrow, ncol, ncell)
resolution  : 0.008333334, 0.008333334  (x, y)
extent      : -180, 180, -60, 90.00001  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs 
data source : E:\Data\Elevation_Data\alt\alt 
names       : alt 
values      : -431, 8233  (min, max)
attributes  :
     ID COUNT
 from: -431     2
 to  : 8233     1

> image(elev, zlim=c(0,1200))

The above command simply plots an image with the necessary values, but I would like a raster with just those limits.

Any thoughts?

Best Answer

Try the commented and reproducible example below. You can assign NA values to your elevation RasterLayer as elev[elev < 0] <- NA and elev[elev > 1200] <- NA.

# Load libraries
library('raster')
library('rgdal')
library('mapview') # interactive map viewing in R

# Get DEM data example
elev <- getData('alt', country = 'URY')

rasterLayer

# Plot elevation data example 
mapview(elev)

# Define and query thresholds 
min <- 50
max <- 300

elev2 <- elev
elev2[elev <= min] <- NA
elev2[elev >= max] <- NA

# Plot elevation with threshold max min
mapview(elev2)

rasterlayer2

print(elev2) # see min and max values

#class       : RasterLayer 
#dimensions  : 612, 648, 396576  (nrow, ncol, ncell)
#resolution  : 0.008333333, 0.008333333  (x, y)
#extent      : -58.5, -53.1, -35.1, -30  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
#data source : in memory
#names       : URY_msk_alt 
#values      : 51, 299  (min, max)

Note: more help and so nice information about rasters in R here Raster Data in R - The Basics