On Aug 11, 2011, at 10:27 AM, Uwe Ligges wrote:

On 11.08.2011 19:22, David Winsemius wrote:

Hmm, when you want to add a level without changing the class of the factor object, you will have to add the level at first and then assign the level to the elements of the object. I'd probably rebuild the whole thing in that case.


All I wanted to do was construct a "not done" label for the NA's in a factor created with cut so they would show up in tabulations. I think the answer to my question is to use `addNA` and then use `levels<-` to change the NA level to "not done". I suppose RTFM is one way to answer the question and that was how I figured out what I now know. Looks like I can use either factor(x, exclude=NULL) or addNA(x.c)

This builds a test factor:

x<-rnorm(100)
is.na(x) <- sample(c(TRUE,FALSE), 100, c(.1,.9) , replace=TRUE)
x.c <- cut(x, seq(-3,3, by=0.5))

# I think these do the same thing:
x.cE <- factor(x, exclude=NULL)
x.cNA <- addNA(x.c)

# Relabel the NA level
levels(x.cNA) <- c(levels(x.c2)[-length(levels(x.c2))], "NotDone")

> table(x.cNA)
x.cNA
(-3,-2.5] (-2.5,-2] (-2,-1.5] (-1.5,-1] (-1,-0.5] (-0.5,0] (0,0.5] (0.5,1] (1,1.5] (1.5,2] 0 0 3 5 16 17 14 14 15 4
  (2,2.5]   (2.5,3]   NotDone
        2         1         9

That seems a bit less baroque than converting to numeric , changing NA's to 0 and then adjusting the factor labels, although I still want to move the not-done level so it is first.

x.cN <- factor(x.cNA, levels=c("NotDone", c(levels(x.cNA)[- length(levels(x.cNA))]))
> table(x.cN)
x.cN
NotDone (-3,-2.5] (-2.5,-2] (-2,-1.5] (-1.5,-1] (-1,-0.5] (-0.5,0] (0,0.5] (0.5,1] (1,1.5] 9 0 0 3 5 16 17 14 14 15
  (1.5,2]   (2,2.5]   (2.5,3]
        4         2         1

As I understood the question, just how to rename the levels was the original question.

Yes, that was how I understood it as well. I was asking what I thought was a related question.


Uwe



______________________________________________
R-help@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.

Reply via email to