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.
Let's consider your function definition. First, you need an extra set of curly brackets.
Second, in English, your function
ttaccepts a single argumentvec.Now let's consider your function call:
In English, you want to evaluate
ttwith the arguments1and2. However, your function only accepts one argument. Therefore you get the error: "Error in tt(1, 2) : unused argument (2)", because the second argument,2is unused.How can we fix this? First, we can define
aandbbased onvec:Now we can call
ttwith one argument, a vector that contains two elements: