Is it possible to evaluate only some of the variables?

Go To StackoverFlow.com

-2

Is it possible to evaluate only some of the variables?

t<- function(a,b,c){a+b+c}
t(1,2,c)

which produces the error

Error in a + b + c : non-numeric argument to binary operator

2012-04-05 02:24
by user182814
What exactly are you expecting/hoping to happen - Dason 2012-04-05 02:36
I want to produce a single variable function from a multivariable function by evaluating all but one of the variables - user182814 2012-04-05 02:44
So in your example you would to make a function of c? Would defining a new function be out of the question. Something like t2=function(c){t(1,2,c)}Dason 2012-04-05 02:46
See: http://stackoverflow.com/questions/6547219/r-project-how-to-bind-function-argument - G. Grothendieck 2012-04-05 03:51


1

You could set some defaults and that way you don't have to input all of the parameters.

fun <- function(a=0, b=0, c=0){return(a + b + c)}
fun(1, 2, 3)
#[1] 6
fun(4, 5)
#[1] 9
fun()
#[1] 0

Note that you probably shouldn't call a function 't' since there is already a fairly important function named t.

I'm guessing you're trying to work on a slightly more complicated example. Otherwise you could just use sum to accomplish this task.


Edit: It seems you just want to turn a multiparameter function into a single parameter function by setting the value for some of the parameters. You can just define a new function that does what you want.

newfun <- function(c){return(fun(1, 2, c))}
newfun(1)
#[1] 4
newfun(5)
#[1] 8
2012-04-05 02:43
by Dason


0

> t<- function(a,b,c){if(missing(c)) { function(c){a+b+c}} else{a+b+c} }
> t(1,2)(4)
[1] 7
> t(1,2)
function(c){a+b+c}
<environment: 0x159956028>
> t(1,2,3)
[1] 6
2012-04-05 02:55
by 42-
Ads