# How to extract values from a raster using R?

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?

• Maths with `raster` objects is just like maths on normal R vectors, so figure out how you would do your computation on a simple vector. You may need to improve your basic R skills first - forget about maps for a while! Then when you do go back to it, test on a small raster first - that one you list is huge and anything you try might take a while. – Spacedman Feb 17 '16 at 8:40
• Have a look at the raster package, or better, directly for the introduction to the raster package. You can read your raster into r by: `install.packages("raster") # install package`, `library(raster) # load package`, `setwd("/private/var/folders/sy/qh_q0tbs29l_j9wfndb6cw5r0000gp/T/RtmpDc7N7c/raster/") # set working directory`, `Your_raster <- raster('r_tmp_2016-02-15_212425_11368_77493.grd') # raster from your file`, `plot(Your_raster)` – user3624251 Feb 17 '16 at 9:19

## 2 Answers

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')
``````

To do a linear stretch on raster data you can use the `stretch` function:

``````library(raster)
r <- raster(nc=10, nr=10)
r[] <- 1:100 * 10
s <- stretch(r)
``````

So you won't need this, but to extract the min and max values you can do:

``````minValue(r)
maxValue(r)
``````