Q:

R - Creating function call within function using relational operator as variable

I am trying to write a function that will apply a user-specified binary operator (e.g. < ) to a raster object. To do so is fairly simple. For example:
selection <- raster::overlay(x = data, fun = function(x) {return(x < 2)}

My issue is that this code would be running within a function, with which I would like to specify both the binary operator and the criteria value (which is 2 in the example above) as variables. For example:
my.func <- function(data, binary_operator, value){
    selection <- raster::overlay(x=data, fun=function(x) {x criteria value})
return(selection)
}

I have tried to construct the function as a call without success.
my.func <- function(data, binary_operator, value){
selection <- raster::overlay(x=data, fun=function(x) {call(sprintf("x %s %s", criteria, value))}
return(selection)

}
Is there a way to construct the call of the second function using variables in the first function?
Thanks for your help.

A:

Write your code like this:
my.func <- function(data, binary_operator, value){
    selection <- raster::overlay(x=data, fun=function(x) binary_operator(x, value))
    return(selection)
}

You need to call this as
my.func(data, `<`, 2)

(with backticks for quotes).  If you want to allow "<" for the operator, you could use do.call:
my.func <- function(data, binary_operator, value){
    selection <- raster::overlay(x=data, fun=function(x) 
        do.call(binary_operator, list(x, value)))
    return(selection)
}

This will work with either form of argument.

