Calculate number of co-occurrences for two vectors
sum(d$rs &amp; d$occ)
#[1] 2


The goal is "...simply counting the number of occurrences that the variables rs and occ appear together." If you feel that your code is long and cumbersome, the vectorization process of R is uniquely capable of speeding up the task without for loops and nested conditionals.

As mentioned in the previous answer, R coerces certain classes onto vectors when specific functions are called on them. The two columns in question are both a series of 1's and 0's. They are numeric values. I would like them to be thought of as TRUE's and FALSE's to evaluate my logical condition. Thanks to the brevity of R code I do not have to literally ask R to do that. As soon as I use the &amp; operator, R will immediately treat all 0's as FALSE and other numbers as TRUE logical values. 

Finally, sum does a similar action but in the opposite direction. It coerces (forces the class) to numeric in order to calculate the sum. It treats TRUE as 1 and 0 as FALSE. In the case of this code, Many complicated relationships are being handled by the R computing engine and, thankfully, not by us.

If you would like the other two values for unique and zero use:

sum(xor(d$rs, d$occ))
[1] 4
sum(!d$rs &amp; !d$occ)
[1] 14


The function xor tests what is called the "exclusive or". So the code read aloud would be "How many pairs have a one in rs or occ, but not in both." The operator ! negates what comes after it. That code would read, "How many pairs have a value that is not 1 in rs and not 1 in occ."