[R-sig-Geo] raster::calc with multiple arguments

Ahmed El-Gabbas elgabass at gmail.com
Wed Jul 29 20:18:51 CEST 2015


Something like this should works:

require(raster)
r <- raster(ncols=36, nrows=18)
r[] <- 1:ncell(r)

fun1 <- function(R, alpha) {
   if(!is.numeric(alpha) | !class(R) %in% c("RasterLayer", "RasterStack")){
# check class type
      stop()
   } else {
      R*alpha
   }
}
r2 <- fun1(R = r, alpha = 10)

###|||||||||||||||||||||||
### or
###|||||||||||||||||||||||

fun2 <- function(..., alpha) {...*alpha}
r3 <- calc(r, function(x){  fun2(x, alpha = 10) } )

all.equal(r2[],r3[]) # both solutions give the same results

------------------------
Regards,
Ahmed

On Wed, Jul 29, 2015 at 7:08 PM, Andy Bunn <Andy.Bunn at wwu.edu> wrote:

> Hi all, likely a dumb question. I want to use raster::calc with a function
> containing more than one argument. This violates the expectation of calc so
> I know the code below shouldn't work but I'm wondering what the best
> alternative is for calculating values for a new raster object from another
> raster object using a function with multiple arguments (e.g., fun2 below).
>
> Regards and thanks in advance, Andy
>
>
> require(raster)
> r <- raster(ncols=36, nrows=18)
> r[] <- 1:ncell(r)
>
> # multiply values by 10
> fun1 <- function(x) { x * 10}
> # multiply values by alpha
> fun2 <- function(x, alpha) { x * alpha}
>
> rc1 <- calc(r, fun1) # works
> rc2 <- calc(r, fun2, alpha=10) # doesn't work
>
>
>         [[alternative HTML version deleted]]
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>

	[[alternative HTML version deleted]]



More information about the R-sig-Geo mailing list