[R-sig-Geo] function parameters in overlay()

Robert J. Hijmans r.hijmans at gmail.com
Fri Dec 17 23:58:50 CET 2010


Agus,

# self contained example...
library(raster)
r1 <- raster(nrow=10, ncol=10)
r1[] = 1:ncell(r1)
r2 <- r1

# base case
fun1 = function(x,y){ a=-1.1867422; s=1.0287373;
return((y-(a+s*x))/sqrt(s^2+1))}
x = overlay(r1, r2, fun=fun1 )

# changing a & s without changing fun2, perhaps clumsy
fun2 = function(x,y,a,s) {return((y-(a+s*x))/sqrt(s^2+1))}
x1 = overlay(r1, r2, fun=function(x,y){fun2 (x, y, a=-1.1867422,s=1.0287373)})
x2 = overlay(r1, r2, fun=function(...){fun2 (..., a=-1.1867422,s=1.0287373)})

# changing a & s without changing fun3, perhaps cleaner
# I believe this works because a and s are defined in the same
environment as fun3
fun3 = function(x,y) { return((y-(a+s*x))/sqrt(s^2+1)) }
a = -1.1867422
s = 1.0287373	
x3 = overlay(r1, r2, fun=fun3)

Best, Robert

On Fri, Dec 17, 2010 at 1:04 PM, Agustin Lobo <alobolistas at gmail.com> wrote:
> Robert,
>
> How can I define parameters in the functions within overlay() ?
> For example:
>
>> fun3 = function(x,y)
> {a=-1.1867422
>  s=1.0287373
>  return((y-(a+s*x))/sqrt(s^2+1))}
>> NmaxDev = overlay(bN1999max,bN2009max,fun=fun2,filename="NmaxDev",overwrite=TRUE,format="EHdr",datatype='FLT4S', NAflag=0)
>
> want it to be something like:
>
>> fun3 = function(x,y,a,b)
> {return((y-(a+s*x))/sqrt(s^2+1))}
>> NmaxDev = overlay(bN1999max,bN2009max,fun=fun2(a=-1.1867422,s=1.0287373),filename="NmaxDev",overwrite=TRUE,format="EHdr",datatype='FLT4S', NAflag=0)
>
> Is it possible or should I redefine the function every time?
>
> Agus
>



More information about the R-sig-Geo mailing list