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

Tara Bridwell tarabridwell at gmail.com
Thu Sep 22 02:44:51 CEST 2011


That was it - works perfectly now.  Thank you Robert.

Tara

On Wed, Sep 21, 2011 at 10:49 AM, Robert J. Hijmans <r.hijmans at gmail.com> wrote:
> Tara,
> raster_ct<- rasterize(coord.plus.value_sp, r,
> fun=function(value) {length(unique(na.omit(value)))})
> This is wrong on two accounts. You do not use the "..." argument and you do
> not pass the vector "value" to rasterize (instead, you redefine it inside
> "fun")
> It should be:
> library(raster)
> r <- raster(ncol=10, nrow=10)
> x <- c(-45, -45, -45, 30, 30, 20, -10, 50, -7)
> y <- c(-25, -25, -25, 148, -148, 46, 23, 0, -69)
> xy <- cbind(x,y)
> species <- c(1, 2, 3, 1, 2, 3, 1, 1, 1)
> x1 <- rasterize(xy, r, field=species, fun=function(x,
> ...){length(unique(na.omit(x))) })
> # as you do not have NA values you can also do this
> x2 <- rasterize(xy, r, species, fun=function(x, ...){length(unique(x)) } )
>
> Best, Robert
> On Wed, Sep 21, 2011 at 10:13 AM, Tara Bridwell <tarabridwell at gmail.com>
> wrote:
>>
>> 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
>>
>> _______________________________________________
>> R-sig-Geo mailing list
>> R-sig-Geo at r-project.org
>> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>
>



More information about the R-sig-Geo mailing list