[R] Help with functions as arguments

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Tue Feb 12 10:40:56 CET 2013


On Tue, Feb 12, 2013 at 7:30 AM, Ian Renner <ian_renner at yahoo.com> wrote:

> Where I am running into trouble is when I want to call function f1 within function f2:
>
> f2(x = 3, z = f1(x))
>
> This returns the error:
>
> "Error in f1(x) : object 'x' not found"
>
> I'm not sure how to define environments within the functions so that the just-defined 'x' may be passed as an argument to f1 within f2.

I think this is a bit like the joke where a man goes to the doctor,
raises his arm up and says "It hurts when I do that", and the doctor
says "well, don't do that then. Next patient!".

Whatever is calling f2 knows what it is passing as the first argument.
It should then know that it wants to pass f1(the first argument) and
so can explicitly put that into the first argument of the f1 call. ie.
your example should be;

f2(x=3, z=f1(3))

What you are trying to do is akin to saying:

f2(x=3, z=f1(that thing I passed to the x parameter, you expect me to
type it in again? I thought computers were supposed to save effort!))

Now, this is different to *defining* f2 to take f1(x) as the default
second parameter to f2:

f2 = function(x,z=f1(x)){y=x*z-2;y}

which is saying that unless the user says otherwise when they call
this function, the second parameter is f1(the first parameter). This
does work as expected.

But the crux is that the terms inside function calls are not executed
as assignments like you thought they were. For one thing, named
function parameters can appear in any order - would you expect x be
defined in the f1(x) if you called f2(z=f1(x),x=9)?

Barry



More information about the R-help mailing list