Leon-Alph
Leon-Alph

Reputation: 87

using character R function

I'm creating a function in R where I'm asking a letter (or a string). Here is an example with a first function:

fun.1<-function(a=2,b=3,c=4) return(a+b^2+c^3)

and another function using the first one:

fun.2<-function(letter.to.test="a",a=2,b=3,c=4){
   if(letter.to.test=="a") {a=0:10} 
   else if(letter.to.test=="b"){b=0:10} 
   else {c=0:10} 
   return(fun.1(a,b,c)) 
}

How may I write fun.2 without the if else functions? In my real code, I have 46 parameters to test, so it's ugly to write 46 if else. Thank you

Upvotes: 1

Views: 104

Answers (5)

Rich Scriven
Rich Scriven

Reputation: 99351

You could substitute the test value into a call to <-. Then evaluate it to change the values.

fun.2 <- function(test = "a", a = 2, b = 3, c = 4) {
    eval(call("<-", as.name(substitute(test)), 0:10))
    fun.1(a, b, c)
}

fun.2()
# [1] 73 74 75 76 77 78 79 80 81 82 83

Upvotes: 1

rawr
rawr

Reputation: 20811

You don't need fun.2

fun.1<-function(a=2,b=3,c=4) return(a+b^2+c^3)

mapply(fun.1, a=1:10, SIMPLIFY = TRUE)
# [1] 74 75 76 77 78 79 80 81 82 83

mapply(fun.1, b=1:10, SIMPLIFY = TRUE)
# [1]  67  70  75  82  91 102 115 130 147 166

Upvotes: 1

Tim
Tim

Reputation: 7464

More general approach:

fun.2 <- function(letter.to.test="a", a=2, b=3, c=4) {
   if (letter.to.test %in% letters[1:3]) {
      assign(letter.to.test, 1:10)
      fun.1(a,b,c)
   }
}

Upvotes: 1

bsbk
bsbk

Reputation: 180

If you want them all assigned to the same value (e.g., 0:10), try this:

fun.2<-function(letter.to.test="a",a=2,b=3,c=4){
  assign(paste(parse(text = letter.to.test)), 0:10)
  return(fun.1(a,b,c)) 
}

Upvotes: 0

cdeterman
cdeterman

Reputation: 19960

You want a switch statement.

fun.2<-function(letter.to.test="a",a=2,b=3,c=4){
   switch(letter.to.test,
      a = {a=0:10},
      b = {b=0:10}, 
      c = c=0:10} 
   )
   return(fun.1(a,b,c)) 
}

Upvotes: 0

Related Questions