Search code examples
rsummary

Summary by Row of a Categorical Variable in R


I have the following matrix

coin.flip<-expand.grid(c("H","T"),c("H","T"),c("H","T"),c("H","T"))

> coin.flip
   Var1 Var2 Var3 Var4
1     H    H    H    H
2     T    H    H    H
3     H    T    H    H
4     T    T    H    H
5     H    H    T    H
6     T    H    T    H
7     H    T    T    H
8     T    T    T    H
9     H    H    H    T
10    T    H    H    T
11    H    T    H    T
12    T    T    H    T
13    H    H    T    T
14    T    H    T    T
15    H    T    T    T
16    T    T    T    T

I would like to get a row by row summary of the counts of H's and T's. I would also like a table of how many row's had 1 T, 2 T's, etc...

Thanks a lot! I've been searching for this answer for a little bit and haven't found anything yet.


Solution

  • > coin.flip$total_H <- rowSums(coin.flip=="H")
    > coin.flip
       Var1 Var2 Var3 Var4 total_H
    1     H    H    H    H       4
    2     T    H    H    H       3
    3     H    T    H    H       3
    4     T    T    H    H       2
    5     H    H    T    H       3
    ....snipped
    > table(coin.flip$total_H)
    
    0 1 2 3 4 
    1 4 6 4 1    
    
    Total T's table is just
    > table(4- coin.flip$total_H )
    
    0 1 2 3 4 
    1 4 6 4 1     # boringly similar to total H table