[R] Factor names & levels

Peter Dalgaard p.dalgaard at biostat.ku.dk
Mon Dec 22 02:30:52 CET 2003


"Gabor Grothendieck" <ggrothendieck at myway.com> writes:

> For it to be well defined, there would need to be a names
> method and a names<- method for the factor class or else 
> the default methods would have to be able to handle factors.

Not only that but other methods for factors need to know about the
names and be able to modify them accordingly, e.g.

> getS3method("levels<-","factor")
function (x, value)
{
    xlevs <- levels(x)
    if (is.list(value))  #something
...
    else {
...
        nlevs <- xlevs <- as.character(value)
    }
    factor(xlevs[x], levels = unique(nlevs))
}

Here, xlevs[x] will not have the same names as x (it gets names from
xlevs if anything) so you'd have to have extra code for setting the
names on the result. 

(Rather interestingly, the factor() function does explicitly retain
names, so there are not quite as many places where they will be lost
as I would have expected.)

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list