rfunctionunused-functions

"Unused argument" error in function (if...else) when putting external vector as argument


I'm trying to set up a function that takes values from a single vector, performs some initial checks and finally does calculations, in case checks found suitable input. Here's a simplified version of the issue I'm facing:

I need a vector, consisting of two placeholders for values

vec <- c(a,b)

Then, I set up the function tt:

tt<-function(vec)
    if(a > b){
        return("ERROR")
    }else{message("ok")}

and enter two test values:

tt(1,2)

...this, however, produces "Error in tt(1, 2) : unused argument (2)". I've tried defining the vector vec(a,b) in other ways, such as:

a<-vec[1]
b<-vec[2]

tt<-function(vec)
    if(a > b){
        return("ERROR")
    }else{message("ok")}

or

tt<-function(vec)
    if(a > b){
        a<-vec[1]
        b<-vec[2]
        return("ERROR")
    }else{message("ok")}

The whole if/else works just fine when I enter the placeholders directly into the function, as in:

tt<-function(a, b)
    if(a > b){
       return("ERROR")
    }else{message("ok")}

tt(1,2)

So I'm assuming the problem must be caused by my inability to put the vector into the function correctly. I'm very grateful for any input on how to phrase this properly for R to understand.


Solution

  • Let's consider your function definition. First, you need an extra set of curly brackets.

    tt<-function(vec){
        if(a > b){
            return("ERROR")
        }else{message("ok")}}
    

    Second, in English, your function tt accepts a single argument vec.

    Now let's consider your function call:

    tt(1,2)
    

    In English, you want to evaluate tt with the arguments 1 and 2. However, your function only accepts one argument. Therefore you get the error: "Error in tt(1, 2) : unused argument (2)", because the second argument, 2 is unused.

    How can we fix this? First, we can define a and b based on vec:

    tt<-function(vec){
        a <- vec[1]
        b <- vec[2]
        if(a > b){
            return("ERROR")
        }else{message("ok")}}
    

    Now we can call tt with one argument, a vector that contains two elements:

    tt(c(1,2))
    #ok
    tt(c(2,1))
    #[1] "ERROR"