[GIS] How to extract values from a raster using R

cartographyrrasterstretch

I'm a beginner at using R software, and I'm attempting to perform a percent linear stretch on the following raster data:

> KBnew

#class: RasterLayer
#dimensions  : 27018, 26389, 712978002  (nrow, ncol, ncell)
#resolution  : 15, 15  (x, y) 
#extent  : 541792.5, 937627.5, 5454772, 5860042 (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=utm +zone=10 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0  
#data source : /private/var/folders/sy/qh_q0tbs29l_j9wfndb6cw5r0000gp/T/RtmpDc7N7c/raster/r_tmp_2016-02-15_212425_11368_77493.grd
#names       : layer  
#values      : 7.712379, 205.2743  (min, max)

… although (if I'm doing this correctly) from what I understand, I need to know the mean and standard deviation of the raster values (which would be contained within the range of 7.712379,205.2743 or min/max values). How do I extract these values, within the minimum/maximum range?

Best Answer

The mean and standard deviation can be calculated using cellStats() from the raster package.

#install.packages(raster)
library(raster)

# example dataset
r <- raster(nrow=18, ncol=36)
r[] <- runif(ncell(r)) * 10

# get mean
cellStats(r,'mean')