Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R language: switch cases on numeric value

I want to switch cases in numeric value, but I can't find a natural way to do this. Here's what I tried:

this leads to syntax error:

fun <- function(x) {
    switch(x,
           0.2=0.1,
           0.9=0.6)
}

this one compiles, but is there a better solution?

fun <- function(x) {
    y <- as.character(x)
    switch(y,
           "0.2"=0.1,
           "0.9"=0.6)
}
like image 353
user3684014 Avatar asked Jul 14 '14 20:07

user3684014


1 Answers

According to the ?switch help page

If the value of EXPR is not a character string it is coerced to integer. If this is between 1 and nargs()-1 then the corresponding element of ... is evaluated and the result returned: thus if the first argument is 3 then the fourth argument is evaluated and returned.

Additionally, the help page provided this example of using a numerical expression

## Numeric EXPR does not allow a default value to be specified
## -- it is always NULL
for(i in c(-1:3, 9))  print(switch(i, 1, 2 , 3, 4))

So when using a numeric switch, only integer values are allowed. Checking that two decimal values are exactly equal isn't always that easy thus it is not allowed. Perhaps there is a better way for you to track this particular condition than using a non-integer numeric value.

like image 100
MrFlick Avatar answered Oct 19 '22 12:10

MrFlick