Search code examples
rcrosstab

Cross table with zero counts


Maybe this is simple, but I could not find a solution. The problem is zero counts in a cross table in R. If all the elements in a row or column of the cross table, the table command does not show that row or column. As far as I can see, there is a solution with tabulate command for single vector case, but I can not find solution for cross tabs.

A simple example of "what I get" and "what I want" is below.

a <- c(rep("a", 4), rep("b", 4))
b <- rep("a", 8)

table(letter1 = a, letter2 = b)

# What I get

#        letter2
# letter1 a
#       a 4
#       b 4

# What I want

#        letter2
# letter1 a b
#       a 4 0
#       b 4 0

Solution

  • You could convert b to a factor and specify appropriate levels.

    table(letter1 = a, letter2 = factor(b, levels = unique(a)))
    #       letter2
    #letter1 a b
    #      a 4 0
    #      b 4 0