1

Let's say I have a function like this:

myFun <- function(arg1, arg2, arg3) {

    if(arg3 == 'A') funA(arg1, arg2)
    else if(arg3 == 'B') funB(arg1, arg2)
    else if(arg3 == 'C') funC(arg1, arg2)

}

Is there a way to not continually repeat arg1, arg2, but somehow construct the call more intelligently? I was looking into match.call but am not sure if it fits my use case.

2
  • Or maybe myFun <- function(arg1, arg2, arg3) get(paste0("fun", arg3))(arg1, arg2) but I'm not sure whether your functions connect as in your example. Commented Jul 23, 2016 at 3:16
  • 1
    @shayaa how do I accept your comment as the best answer? Commented Jul 23, 2016 at 4:52

3 Answers 3

2

You could use match.arg() along with paste0().

myFun <- function(arg1, arg2, arg3) {
    stopifnot(arg3 %in% c("A", "B", "C"))
    paste0("fun", arg3)
}

This will trigger an error if arg3 is not in the choices c("A", "B", "C")

myFun(arg3 = "A")
# [1] "funA"
myFun(arg3 = "defg")
# Error: arg3 %in% c("A", "B", "C") is not TRUE 

So we can just use that in do.call() to call it with the other arguments.

myFun <- function(arg1, arg2, arg3) {
    stopifnot(arg3 %in% c("A", "B", "C"))
    do.call(paste0("fun", arg3), list(arg1, arg2))
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a clean way to check if arg3 is an accepted value? I.E. if arg3 = 'dafjgadf' what will happen?
@FrankP. - I revamped the answer.
1

Can your functions actually be pasted together or is that just an effect of the example? If so, consider this:

get(paste0("me", "an"))(1:5)
[1] 3

I created the function by pasting its name together. So in your example:

myFun <- function(arg1, arg2, arg3) {

get(paste0("fun", arg3))(arg1, arg2)

}

Comments

1

Here is an alternative approach using switch

myFun <- function(arg1, arg2, arg3){
    switch(arg3, 
        A = {
         out <- funA(arg1, arg2)
        },
       B = {
         out <- funB(arg1, arg2)
       },
       C= {
         out <- funC(arg1, arg2)
      },
     stop("Enter something that makes sense!")
   )
  return(out)
}

funA <- function(x,y) mean(c(x,y))
funB <- function(x,y) sum(c(x,y))
funC <- function(x,y) var(c(x,y))

myFun(3, 4, "A")
#[1] 3.5
myFun(3, 4, "B")
#[1] 7
myFun(3, 4, "C")
#[1] 0.5
myFun(3, 4, "D")

Error in myFun(3, 4, "D") : Enter something that makes sense!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.