[R-sig-Geo] Determining unique values in a raster

Tara Bridwell tarabridwell at gmail.com
Wed Sep 21 19:13:51 CEST 2011


I am trying to determine the unique values within a raster, but am
having trouble.  Here is some sample base data:

require(raster)
r <- raster(ncol=10, nrow=10)
r[]=1:ncell(r)

x <- c(-45, -45, -45, 30, 30, 20, -10, 50, -7)
y <- c(-25, -25, -25, 148, -148, 46, 23, 0, -69)
value <- c(1, 2, 3, 1, 2, 3, 1, 1, 1)
coord.plus.value <- cbind(x, y)
coord.plus.value_sp <- SpatialPoints(coord.plus.value)

>From here I want to find the number of unique values in each cell of
the raster (i.e. 'richness').  To get around the need for an
na.rm=TRUE need for these functions, the documentation for rasterize
suggests:

Note that the function must take an na.rm argument, either explicitly
or through 'dots'. This means that fun=lenght fails, but
fun=function(x,...)lenght(x) works (but ignores the na.rm argument. To
use the na.rm argument you can use a function like this
fun=function(x,na.rm){if (na.rm) length(na.omit(x)) else (length(x)},
or use a function that removes NA values in all cases, like this
function to compute the number of unique values "richness":
fun=function(x, ...){length(unique(na.omit(x)))}.
When I try this for my code:
raster_ct<- rasterize(coord.plus.value_sp, r, fun=function(value)
{length(unique(na.omit(value)))})

I still get the following error:
Error in FUN(X[[1L]], ...) : unused argument(s) (na.rm = TRUE)

Does anyone have any thoughts on why this is happening?  I have tried
defining the function outside of the rasterize code but then I end up
with the same value in all cells.

Thank you,
Tara Bridwell



More information about the R-sig-Geo mailing list