Search code examples
rsortingr-factor

How to sort factor levels in a table output in R?


Suppose I have two binary variables:

group <- rbinom(100,1,0.6)
y <- rbinom(100,1,0.3)

table(group,y)
         y
    group  0  1
        0 26 13
        1 42 19

How to table out or sort the table output in this format:

     y
group  1  0
    0 13 26
    1 19 42

Solution

  • Depending on what bigger problem you are trying to solve, either one of these approaches might be helpful. For reference, here is what I get initially:

    > set.seed(1)
    > group<-rbinom(100,1,0.6)
    > y<-rbinom(100,1,0.3)
    > 
    > table(group,y)
         y
    group  0  1
        0 28 15
        1 42 15
    

    You can redefine y to be a factor with your own choice of ordering of the factor levels and then tabulate:

    > table(group,factor(y,levels=c("1","0")))
    
    group  1  0
        0 15 28
        1 15 42
    

    Or you can run the table as above and then sort the columns of the output:

    > table(group,y)[,c("1","0")]
         y
    group  1  0
        0 15 28
        1 15 42