[Rd] Possible bug in factor (PR#531)

Thomas Lumley thomas@biostat.washington.edu
Tue, 2 May 2000 17:05:51 -0700 (PDT)


On Wed, 3 May 2000 mh.smith@auckland.ac.nz wrote:

> The expressions
> 
> > x<-factor(x)
> 
> and
> 
> > class(x)<-"factor"
> 
> behave differently when x is already an ordered factor.  It may not be a
> bug but it caught me out when I was trying to remove the "orderedness"
> from a factor variable. The following R code illustrates the difference.
> Is this difference between the 2 commands desirable?

Yes.  factor, like as.factor, turns its argument into a factor. As it
already is a factor this doesn't do anything. 

class(x)<-"factor" says that x is a factor and has no other class.  In
general it is a bad idea to explicitly set the class of a variable
like this (except when you're constructing the object).  This is for two
reasons. One, you usually don't want to remove other classes. Two, x may
not be a factor, and just setting its class to "factor" may leave it in an
inconsistent state. 
Eg
> x<-1:10
> class(x)<-"factor"
> x
NULL
Levels:

In this particular case you know that x has class c("ordered","factor")
and that you want it to have class "factor", so it is harmless. It still
may be unnecessary -- eg if you just want it to have treatment contrasts
rather than polynomial contrasts you can use C() or constrasts()<-.

	-thomas

Thomas Lumley
Assistant Professor, Biostatistics
University of Washington, Seattle

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-devel mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-devel-request@stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._