About

Sometimes it is important to know the number/proportion of cells in a raster that meet a certain threshold. This can easily be done as follows:

Creating sample raster

set.seed(123)
r <- raster(nrow = 10, ncol = 10) # Creates the raster.
r[] <- rnorm(1:ncell(r)) # Fills the raster with random values around 0.
plot(r) # Visualizes the raster.

Count number of cells in the raster

ncell(r) # Counts the number of cells in the raster.
## [1] 100

Count cells with values above 0.3

sum(r[] > 0.3) # Returns sum of number of cells with pixel values above 0.3.
## [1] 41

Get proportion of cells with pixel values above 0.3

sum(r[] > 0.3) / ncell(r) # Divides sum of cells above 0.3 by total number of cells.
## [1] 0.41

As a percentage

print(paste0(sum(r[] > 0.3) / ncell(r) * 100, '%')) 
## [1] "41%"

Application

Let’s assume our raster showed suitability scores of our study area for a specific species. So, we are aware that 41 % of our predicted area is suitable for the species. This value is normally useful when working around significance of the built model before interpreting results.

References

Allaire, JJ, Yihui Xie, Jonathan McPherson, Javier Luraschi, Kevin Ushey, Aron Atkins, Hadley Wickham, Joe Cheng, Winston Chang, and Richard Iannone. 2022. Rmarkdown: Dynamic Documents for r. https://CRAN.R-project.org/package=rmarkdown.
Bivand, Roger S., Edzer Pebesma, and Virgilio Gomez-Rubio. 2013. Applied Spatial Data Analysis with R, Second Edition. Springer, NY. https://asdar-book.org/.
Hijmans, Robert J. 2022. Raster: Geographic Data Analysis and Modeling. https://rspatial.org/raster.
Pebesma, Edzer J., and Roger S. Bivand. 2005. “Classes and Methods for Spatial Data in R.” R News 5 (2): 9–13. https://CRAN.R-project.org/doc/Rnews/.
Pebesma, Edzer, and Roger Bivand. 2022. Sp: Classes and Methods for Spatial Data. https://CRAN.R-project.org/package=sp.
Qiu, Yixuan. 2021. Prettydoc: Creating Pretty Documents from r Markdown. https://github.com/yixuan/prettydoc.
R Core Team. 2022. R: A Language and Environment for Statistical Computing. Vienna, Austria: R Foundation for Statistical Computing. https://www.R-project.org/.
Xie, Yihui. 2014. “Knitr: A Comprehensive Tool for Reproducible Research in R.” In Implementing Reproducible Computational Research, edited by Victoria Stodden, Friedrich Leisch, and Roger D. Peng. Chapman; Hall/CRC. http://www.crcpress.com/product/isbn/9781466561595.
———. 2015. Dynamic Documents with R and Knitr. 2nd ed. Boca Raton, Florida: Chapman; Hall/CRC. https://yihui.org/knitr/.
———. 2022. Knitr: A General-Purpose Package for Dynamic Report Generation in r. https://yihui.org/knitr/.
Xie, Yihui, J. J. Allaire, and Garrett Grolemund. 2018. R Markdown: The Definitive Guide. Boca Raton, Florida: Chapman; Hall/CRC. https://bookdown.org/yihui/rmarkdown.
Xie, Yihui, Christophe Dervieux, and Emily Riederer. 2020. R Markdown Cookbook. Boca Raton, Florida: Chapman; Hall/CRC. https://bookdown.org/yihui/rmarkdown-cookbook.