Include levels of zero count in result of table()

Convert your variable to a factor, and set the categories you wish to include in the result using levels. Values with a count of zero will then also appear in the result:

y <- c(0, 0, 1, 3, 4, 4)
table(factor(y, levels = 0:5))
# 0 1 2 3 4 5 
# 2 1 0 1 2 0 

Leave a Comment