[R-sig-Geo] Matching values in the raster package

pgalpern pgalpern at gmail.com
Mon Oct 31 02:55:00 CET 2011


Hello!

Wondering if there is an efficient raster package approved way of 
comparing values to a lookup list (as one would using the %in% operator).

## Make a random raster with cell values 0 through 9 for illustration
library(raster)
randomRaster <- raster(ncol=25, nrow=25)
randomRaster[] <- floor(abs(runif(ncell(clumpyRaster))*10))

## Now make a new binary raster in which the cells with values 2, 4 or 6 
are set
## This fails probably because %in% has not been implemented!
newRaster <- randomRaster %in% c(2, 4, 6)

## My clunky alternative
newRaster <- calc(randomRaster, function(x) sapply(x, function(y) if (y 
%in% c(2, 4, 6)) return(1) else return(0)))

This works, but is messy.  Am I missing a better way?

By the way--raster package is a revolution (fine work is much appreciated).

Thanks,
Paul

-- 
Paul Galpern, PhD Candidate
Natural Resources Institute
70 Dysart Road
University of Manitoba
Winnipeg, Manitoba, Canada R3T 2M6
http://borealscape.ca



More information about the R-sig-Geo mailing list