Skip to content
Prev 317362 / 398506 Next

Help with functions as arguments

On Tue, Feb 12, 2013 at 09:38:19AM +0100, Rainer M Krug wrote:
If you really want to force it, you could use

    f2(x = X <- 3, z = f1(X))

I'd always recommend Rainer's two-line version (first assign X, then
invoke f2), for reasons of legibility / code maintainability and others.

If you want to evaluate f1 inside f2, then you can rewrite f2 to take
f1 as an argument:

    f2 <- function(x, f) { z <- f(x); return(x * z - 2); }

and invoke that as follows:

    f2(x = 3, f = f1)

If the value of z always depends in some way on x, passing in the
function to compute z this way is much better than to write f2 as
though x and z are independent variables.

Best regards, Jan