简体   繁体   中英

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

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)
   }
}

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

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

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)) 
}

If you want them all assigned to the same value (eg, 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)) 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM