[R] expression input to a function

Duncan Murdoch murdoch.duncan at gmail.com
Wed May 4 14:13:57 CEST 2016


On 04/05/2016 7:11 AM, Naresh Gurbuxani wrote:
> I am trying to write a function, which can be made very general if one of the inputs can be an expression.  How can this be done?
>
>
> For example, to find root of a function, I would like to say
>
> my.func <- function(x) {x^3 + 2 * (x^2) - 7}
>
> x.left <- 0
> x.right <- 2
> n.iterations <- 0
>
> find.root <- function(my.func, x.left, x.right) {
>   # code here
> return(c(x.mid, n.iterations))
> }
>
> The above method clearly does not work.

You are taking the right approach.  You can pass functions as arguments 
to other functions; they are "first class objects".  For example:

evaluate <- function(f, x) f(x)

evaluate(my.func, 3)

would give the same result as my.func(3).

For your find.root function, just write the search in find.root using 
the name of the argument (which for didactic purposes I'd recommend be 
different from the actual function name, but it'll be fine in practice).

It is also possible to pass expressions that aren't in functions, but it 
gets tricky, and you shouldn't do that in your first attempt.

Duncan Murdoch



More information about the R-help mailing list