Re: [R] switch and factors

From: Joshua Wiley <jwiley.psych_at_gmail.com>
Date: Mon, 14 Mar 2011 02:55:45 -0700

Dear Baptiste,

On Tue, Mar 8, 2011 at 6:02 PM, baptiste auguie <baptiste.auguie_at_googlemail.com> 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

This strikes me as similar to a discussion awhile back about whether factors should behave primarily as their string levels or underlying numeric representation:

> dput(factor('x', levels = c('y', 'x')))
structure(2L, .Label = c("y", "x"), class = "factor")

which of course also depends on whether methods are explicitly defined:

> dat <- factor('x', levels=c('y', 'x'))
> as.vector(dat) ## has methods

[1] "x"
> c(dat) ## does not

[1] 2

Because factors sort of live between worlds, "expecting" may be a bit of a risky thing.

Cheers,

Josh

> 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.

-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/

______________________________________________
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.
Received on Mon 14 Mar 2011 - 10:01:30 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 14 Mar 2011 - 10:40:21 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive