[R] switch and factors
baptiste auguie
baptiste.auguie at googlemail.com
Tue Mar 15 02:35:14 CET 2011
Hi,
It is indeed documented but I'd misinterpreted it, my mistake. I made
the wrong assumption that switch would have a factor method which
would use the string levels, but that just isn't the case.
Thanks for the clarification anyway,
baptiste
On 14 March 2011 22:22, Allan Engelhardt <allane at cybaea.com> wrote:
> Maybe I am misunderstanding you, but I think it is documented? The help
> page says
>
> switch(EXPR, ...)
> [...]
> If the value of ‘EXPR’ is not a character string it is coerced to
> integer. [...]
>
>
> Since
>
> is.character( factor('x', levels=c('y', 'x')) )
> [1] FALSE
>
>
> you get
>
>> as.integer( factor('x', levels=c('y', 'x')) )
>
> [1] 2
>
>
> from the "coerced to integer" part? Therefore the second statement (y) is
> evaluated regardless of the label ("y"=).
>
> Allan
>
> On 09/03/11 02:02, baptiste auguie wrote:
>>
>> 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
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
--
____________________
Dr. Baptiste Auguié
Departamento de Química Física,
Universidade de Vigo,
Campus Universitario, 36310, Vigo, Spain
tel: +34 9868 18617
http://webs.uvigo.es/coloides
More information about the R-help
mailing list