[R] looping over factors

Liaw, Andy andy_liaw at merck.com
Fri Jan 30 22:54:47 CET 2004


The problem is this: 

> b <- factor(letters[1:3])
> str(b[1])
 Factor w/ 3 levels "a","b","c": 1
> for (i in b) str(i)
 int 1
 int 2
 int 3

So seems like the for loop had drop the factor attribute for `i'.  This
doesn't happen when one simply subset `b':

> for (i in b) str(b[i])
 Factor w/ 3 levels "a","b","c": 1
 Factor w/ 3 levels "a","b","c": 2
 Factor w/ 3 levels "a","b","c": 3

Andy

> From: Samuelson, Frank*
> 
> How does one loop over factors?  Perhaps this is a newbie question.
> I tried:
> 
> > b
> [1] caseX caseY caseZ
> Levels: caseX caseY caseZ
> > length(b)
> [1] 3
> >
> > for (i in b) {
> +   print (b == i) ;
> +   print (i);
> + }
> [1] FALSE FALSE FALSE
> [1] 1
> [1] FALSE FALSE FALSE
> [1] 2
> [1] FALSE FALSE FALSE
> [1] 3
> >
> 
> But that strangely doesn't work.  I must protest
> the implications of the above.  i , as an iterator,
> is supposed take on values from b, but never is it equivalent
> to any of the values in b.  The above works correctly for 
> numbers or arrays of character strings.   What's up with factors?
> 
> Thanks for any help.
> 
> -Frank
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
> 
> 


------------------------------------------------------------------------------
Notice:  This e-mail message, together with any attachments,...{{dropped}}




More information about the R-help mailing list