[R] Evaluating a multivariable function XXXX

Duncan Murdoch murdoch.duncan at gmail.com
Sat May 7 15:05:02 CEST 2011


On 11-05-07 4:06 AM, Dan Abner wrote:
>>
>> Hello everyone,
>>
>> I have the following R code for a multivariable function:
>>
>>
>>> fn2<-function(x,y,z){(y+2*z)/(5*y-x*z)}
>>>
>>> fn2(-5,-2,3)
>> [1] 0.8
>>
>>
>>
>> No problems.
>>
>> ===
>>
>> If, however, I call the function using a vector substitution for the
>> arguments, R sees this as 3 separate calls to the function while supplying
>> only the first argument:
>>
>>> in2<-c(-5,-2,3)
>>> in2
>> [1] -5 -2  3
>>>
>>> fn2(in2)
>> Error in fn2(in2) : argument "y" is missing, with no default
>>
>> ===
>>
>> How should I call the function using the vector substitution method so that
>> R sees that this is a single call to the function that supplies all 3 of the
>> arguments?

The simplest way is to write a new wrapper function:

fn3 <- function(xyz) fn2(xyz[1], xyz[2], xyz[3])

You can also do it with do.call:

do.call(fn2, as.list(in2))

Duncan Murdoch



More information about the R-help mailing list