# Include non-raster object in overlay function in R

I have two raster objects and I would like to calculate values of the first conditional on values in the second. I am currently using the overlay function, but unfortunately I can't seem to pass non raster objects into the function.

As a toy example, r1 includes the values, r2 includes the conditions, and depending on the value of r2, I want to multiply r1 by a value (either .25, .5 or .75). (I know in this example I could just replace 1 with .25, etc. but I just created this as an example).

``````r1 = raster(nrow=5,ncol=5)
r2 = raster(nrow=5, ncol=5)
r1[] = runif(length(r1))
r2[] = round(runif(ncell(r1),min=1,max=3))

f_calcIt = function(a,b){
z = rep(NA,length(a))
i = which(b == 1)
z[i] = a[i] * .25
i = which(b == 2)
z[i] = a[i] * .50
i = which( == 3)
z[i] = a[i] * .75
return(z)
}b

out = overlay(r1,r2, fun = f_calcIt)
``````

This works, but I would like to do is include the scalars (0.25,0.50,.075) that are currently hardcoded in the function as a vector, and import into the function. For example,

``````d = c(.25,.50,.75)

f_calcIt = function(a,b, d){
z = rep(NA,length(a))
i = which(b == 1)
z[i] = a[i] * d
i = which(b == 2)
z[i] = a[i] * d
i = which(b == 3)
z[i] = a[i] * d
return(z)
}
``````

However, the use of this function returns an error that the formula is not vectorized.

Outside of creating a mirror raster with the scalar values in every cell, is there a way to accomplish this using overlay?

The reason that I would like to do so, (and assume others would also), is because it is not always convenient to hardcode values into function, especially if you want to reuse the functions.

You're trying to do two things at once: reclassify the values of `r2` and then multiply those by `r1`. Instead, do them separately:

``````d <- 1:3/4
out = overlay(r1, calc(r2, fun=function(i) d[i]), fun="*")
``````

It is, of course, your responsibility to ensure that the values of `r2` are all valid indexes into array `d`.

whuber showed the way, but here's another way to get there (using the functions that match the operations he suggests)

``````d <- c(.25,.50,.75)

m <- cbind(1:3, d)
r3 <- reclassify(r2, m)
out <- r1 * r3
``````
• Thanks @RobertH. What would I do in the case where d[] is not simply a vector of values, but rather different equations? I can post this as a separate question if this makes it easier. – user44796 Apr 23 '15 at 18:00
• A simple, perhaps inefficient way, would be to run all three equations for all cells. Make a RasterStack 's' of the three (or n) layers, and then use x <- stackSelect(s, r2) – Robert Hijmans Apr 24 '15 at 1:41