Skip to content
Back to formatted view

Raw Message

Message-ID: <6roeskmew0.fsf@bates4.stat.wisc.edu>
Date: 2004-01-31T13:22:39Z
From: Douglas Bates
Subject: looping over factors
In-Reply-To: <87vfmt3yuv.fsf@lumen.indyrad.iupui.edu>

mmiller3 at iupui.edu (Michael A. Miller) writes:

> >>>>> "Samuelson," == Samuelson, Frank* <Samuelson> writes:
> 
>     > How does one loop over factors? 
> 
> You can loop on the levels of your factor:
> 
> > b<-factor(c('caseX','caseY', 'caseZ', 'caseX'))
> > b
> [1] caseX caseY caseZ caseX
> Levels: caseX caseY caseZ
> > for ( i in levels(b) ) { print(i) }
> [1] "caseX"
> [1] "caseY"
> [1] "caseZ"

I don't think that will be what is intended.  The levels attribute is
the distinct character representations of values in the factor.  It
need not be the same length as the factor itself.

> myfac = factor(sample(LETTERS, 100, replace = TRUE))
> table(myfac)
myfac
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 
6 2 4 5 2 3 7 6 3 7 6 3 8 3 1 3 3 5 2 4 2 2 5 4 2 2 
> length(levels(myfac))
[1] 26

By default the levels attribute is sorted lexicographically.

> for (ch in levels(myfac)) print(ch)
[1] "A"
[1] "B"
[1] "C"
[1] "D"
...
[1] "Y"
[1] "Z"

To iterate over the elements of myfac as character strings, use
as.character

> for (ch in as.character(myfac)) print(ch)
[1] "X"
[1] "L"
[1] "M"
[1] "W"
[1] "W"
...
[1] "E"
[1] "G"
[1] "H"

Hope this helps.