Search code examples
rtabulate

Add a factor level to a table


I have built a contingency table from a column in a dataframe:

> dat <- data.frame(x = c(1, 1, 3))
> table(dat)
x
1 3 
2 1

I want to add a "column" to the table for the missing factor levels (in this case "2") with a count of 0. The result should look like this:

> table(dat)
x
1 2 3 
2 0 1

I have searched the site and found many similar questions, but while they use the term "table" in the question title and body, they all actually ask about dataframes.


Solution

  • You need to explicitly specify the levels, i.e.

    table(factor(dat$x, levels = 1:3))
    
    # 1 2 3
    # 2 0 1