[R] switch and factors

baptiste auguie baptiste.auguie at googlemail.com
Wed Mar 9 03:02:31 CET 2011


Dear list,

Reading the help page for ?switch didn't give me more than a hint at
what's going on here,

x = 5
y = 2

foo <- function(a="x"){
     switch(a, "x" = x,
                     "y" = y)
}

foo(factor('x', levels=c('y', 'x')))

# 2

It seems that switch, when given a factor, uses the numeric codes
rather than the string levels as I would have naively expected. Is
this deliberate, should it be mentioned on the help page? I had an
input that had been invisibly converted to a factor by data.frame();
using switch resulted in serious confusion.

Thanks,

baptiste



More information about the R-help mailing list