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)
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With