Search code examples
rr-factor

R - obtaining the levels in a factor


I am trying to write a loop which needs to be able to identify the levels in a factor. I am struggling with obtaining the levels

For example:

x<-c("male","female","male","male")
x<-as.factor(x)

What I am trying to achieve is something like e.g.

>x.level[1]
male 
>x.level[2]
female

How can I create x.level?


Solution

  • You mean something like this...?

     x <- relevel(x, ref="male")  # use `relevel` just to reorder levels
    > x.level <- levels(x)
    > x.level[1]
    [1] "male"
    > x.level[2]  
    [1] "female"