Tim,

The function must return a value for each cell, preferably in a vectorized
way (as in the example below), or otherwise at least in a way that can be
used by apply (which I think is the approach you need if you must use
'which'). See below.

Robert


library(raster)
# generate some example data
t1 <- c(8, 5, 7, 1, 4, 3, 2, 6, 9)
t2 <- c(9, 6, 7, 4, 5, 3, 1, 2, 8)
t3 <- c(9, 6, 7, 4, 5, 3, 1, 2, 8)

tt <- cbind(t1, t2, t3)

# vectorized
bi2 <- function(x){ (x[,1]==1 + 1) != (x[,2]==2) & ((x[,1]==1) - 1) !=
(x[,3]==2) }
# "for apply"
bi2a <- function(x){ (x[1]==1 + 1) != (x[2]==2) & ((x[1]==1) - 1) !=
(x[3]==2) }

bi2(tt)

bi2a(tt)
# no good but works because this is OK:
apply(tt, 1, bi2a)


# example data
r1 <- raster(nrows=10, ncols=10)
values(r1) <- rbinom(100, size = 5, prob=0.5)
r2 <- r1+1
r3 <- r1+2
r <- stack(r1, r2, r3)

# the calc function doesn't work
mycalc <- calc(r, fun=bi2)

mycalc2 <- calc(r, fun=bi2a)




On Mon, Nov 7, 2011 at 11:03 PM, Tim Haering <gnireaht@googlemail.com>wrote:

> Dear list members,
>
> has somebody experience in analysing raster* objects with logical
> functions?
> Consider following example:
> # define a logical function
> bi <- function(x){ which(x==1) + 1 != which(x==2) & which(x==1) - 1 !=
> which(x==2) }
> # generate some example data
> t1 <- c(8, 5, 7, 1, 4, 3, 2, 6, 9)
> t2 <- c(9, 6, 7, 4, 5, 3, 1, 2, 8)
> # function works correct
> bi(t1)
> bi(t2)
>
> I would like to use this function on a raster stack, but don't know how.
> Can someone please help me?
> # example data
> r1 <- raster(nrows=10, ncols=10)
> values(r1) <- rbinom(100, size = 5, prob=0.5)
> r2 <- r1+1
> r3 <- r1+2
> r <- stack(r1, r2, r3)
>
> # the calc function doesn't work
> mycalc <- calc(r, fun=bi)
>
> Thanks a lot.
>
> TIM
>
> ______________________________**_________________
> R-sig-Geo mailing list
> R-sig-Geo@r-project.org
> https://stat.ethz.ch/mailman/**listinfo/r-sig-geo<https://stat.ethz.ch/mailman/listinfo/r-sig-geo>
>

	[[alternative HTML version deleted]]

