[R] Levels number of a factor object

Marc Schwartz MSchwartz at medanalytics.com
Fri Jan 23 15:33:23 CET 2004


On Fri, 2004-01-23 at 08:24, Laurent Houdusse wrote:
> Hi all!
> 
>     How to retrieve the levels number of a factor object?
>     See this code:
>     groups<-gl(4,10)
>     I want to retrieve the number of levels (4) of my object "groups"
>     I tried groups.levels but this don't work
> 
>     Thanks
> 
> 
> Laurent Houdusse 
> Analyste Programmeur


Use nlevels() for the number of levels and levels() to get the actual
level values:

> groups <- gl(4, 10)
> groups
 [1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 4 4 4 4
[35] 4 4 4 4 4 4
Levels: 1 2 3 4

> nlevels(groups)
[1] 4

> levels(groups)
[1] "1" "2" "3" "4"

See ?nlevels and ?levels for more information.

HTH,

Marc Schwartz




More information about the R-help mailing list