[R] Help with functions as arguments

David Winsemius dwinsemius at comcast.net
Tue Feb 12 18:18:44 CET 2013


On Feb 12, 2013, at 12:38 AM, Rainer M Krug wrote:

> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> On 12/02/13 08:30, Ian Renner wrote:
>> Hi,
>> 
>> I am trying to write a function which defines some arguments, then uses those arguments as 
>> arguments of other function calls. It's a bit tricky to explain, so a simple example will have
>> to suffice. I imagine this has a simple solution, but perusing through environments and other
>> help lists has not helped. Suppose I have two functions:
>> 
>> 
>> f1 = function(a) { b = a + 1 b } f2 = function(x, z) { y = x*z -2 y }

I assume that some carriage returns have ben lost and that this is meant:

> f1 = function(a) { b = a + 1; b }; f2 = function(x, z) { y = x*z -2; y }

>> 
>> 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"
> 
> Obviously easiest:
> 
> X <- 3
> f2(X=x, Z=f1(X))

I think there was some switching of capitals there, but assume this was meant:

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


Also possible would be:

> > f2(x, z=f1(x<-3) )
[1] 10

Using f1(x<-3) creates a value of 'x' in the global environment and the result is passed to `f1` (although not as a named argument since f1 is expecting a formal named "b") and then f1(3) is passed to z:

> f1(3)
[1] 4
> f2(3, 4)
[1] 10

This would seem to be a method of creating mildly obfuscated code, so I'm not really recommending it. I would think the more natural way would be creation of a constrained version of f2

f3 <- function(x) { f2(x, f1(x) }

-- 
David.

> 
> Your solution does not work, as the f1(x) is evaluated and the value is passed on to f1, and your
> x is an argument and *only in the function f2* available (= in this context *no* assignment).
> 
> I remember something similar, and the solution had to do with eval() and quote() and friends -
> i.e. you have to only evaluate f(x) *inside* the function f2 - but unfortunately I do not remember
> details.
> 
> Cheers,
> 
> Rainer
> 
> 
> 
>> 
>> 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.
>> 
>> Any help would be greatly appreciated!
>> 
>> Ian Renner [[alternative HTML version deleted]]
>> 


David Winsemius
Alameda, CA, USA



More information about the R-help mailing list