R idiom for switch/case

r, switch-statement

Solution

I think I came up with something I like better:

## Vector-switch
vswitch <- function(EXPR, ...) {
    vars <- cbind(...)
    vars[cbind(seq_along(EXPR), match(EXPR, names(list(...))))]
}

compute.quantiles <- function(mu, type) {
  stopifnot(length(mu) == length(type))

  vswitch( type,
    a = 6.3523 * mu^2,
    b = 234.23 * mu,
    c = mu + mu^2/(9.8 * ((mu-0.3)/3)^(6/7)+0.19),
    d = 56.345 * mu^1.5,
    e = 0.238986 * mu^2,
    f = mu + 1.1868823 * mu^2)
}

With the matrix-indexing code in just 2 lines, I think it's ok for my too-clever-code threshold. =)

Problem

I've got some R code that looks basically like this: ``` compute.quantiles <- function(mu, type) { ## 'mu' and 'type' are vectors of the same length var <- ifelse(type=='a', 6.3523 * mu^2, ifelse(type=='b', 234.23 * mu, ifelse(type=='c', {s <- 9.8 * ((mu-0.3)/3)^(6/7)+0.19; mu + mu^2/s}, ifelse(type=='d', 56.345 * mu^1.5, ifelse(type=='e', 0.238986 * mu^2, ifelse(type=='f', mu + 1.1868823 * mu^2, NA )))))) # ...then do something with var... } ``` Some sample input & output: ``` print(compute.quantiles(2:4, c('c','d','e'))) [1] 2.643840 292.777208 3.823776 ``` That works correctly, but it's kind of ugly with the deep nesting, so I'm wondering if there's a different idiom that works better. Anyone have a suggestion? If `switch()` accepted a vector as its first argument, that would work nicely, but it just takes a scalar.

Original source