An Eager Avocado

Eager Avocado

I give myself very good advice, but I very seldom follow it.

How much harm can nested if's do?

,

The definition of a(), b(), and sw() below achieve the same effect with different implementations: if else, nested if, and switch

a <- function(x) {
    if (x == 'A') {
        paste('Apple')
    } else if (x == 'R') {
        paste('Ready')
    } else if (x == 'N') {
        paste('Novel')
    } else if (x == 'G') {
        paste('Ginger')
    } else {
        paste("Bingo")
    }
}

b <- function(x) {
    ifelse (x == 'A', paste('Apple'),
            ifelse(x == 'R', paste('Ready'),
                  ifelse(x == 'N', paste('Novel'),
                         ifelse(x == 'G', paste('Ginger'),
        paste("Bingo")))))
}

sw <- function(x) {
    switch (x,
        A = paste('Apple'),
        R = paste('Ready'),
        N = paste('Novel'),
        G = paste('Ginger'),
        "Bingo"
    ) 
}

Timing

microbenchmark(a('R'), b('R'), sw('R'), times=1000)
## Unit: microseconds
##     expr   min     lq     mean median     uq    max neval cld
##   a("R") 2.250 2.4375 2.877913 2.5685 2.8615 15.950  1000  b 
##   b("R") 4.891 5.2855 6.250598 5.5870 6.1225 22.822  1000   c
##  sw("R") 1.796 1.9850 2.341278 2.1080 2.3530 16.123  1000 a