Skip to content

Counting two factors at the same time

4 messages · Henrique Dallazuanna, Fabrice DELENTE, David Winsemius

#
Hello.

I'm trying to count string data that correspond to a given
condition in two factors of the same length.

For example, I have one factor

[ 'A', 'B', 'A', 'C', 'B', 'D', 'B' ]

and another is 

[ '1', '2', '2', '3', '2', '2', '3' ]

I'd like to count the occurences of 'B' and '2' (so in my example, I should
get 2 as an answer, since there are 2 'B' that correspond to '2' in the
other factor).

I tried doing it with loops (looping on one factor for 'B', looking for
the corresponding value in the second factor, and incrementing a counter
when the corresponding value is '2'), but I didn't succeed, and I know it's
not the R-way.

Any hint or direction?

Thanks.
#
Try this;

        
On Fri, Jan 22, 2010 at 4:51 PM, Fabrice DELENTE <fdelente at mail.cpod.fr> wrote:

  
    
#
Thanks for the incredibly fast answer! I'll give this a shot!
#
On Jan 22, 2010, at 1:58 PM, Fabrice DELENTE wrote:

            
Here's another R-way:

 > lets<-factor(c( 'A', 'B', 'A', 'C', 'B', 'D', 'B'))
# you did say they were factors, right?
 > nums <- factor(c('1', '2', '2', '3', '2', '2', '3'))
 > lets=="B"
[1] FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE
 > sum(lets=="B" & nums=="2")
[1] 2