Include levels of zero count in result of table()

RCountMissing Data

R Problem Overview


I have a vector 'y' and I count the different values using table:

y <- c(0, 0, 1, 3, 4, 4)
table(y)
# y
# 0 1 3 4 
# 2 1 1 2 

However, I also want the result to include the fact that there are zero 2's and zero 5's. Can I use table() for this?

Desired result:

# y
# 0 1 2 3 4 5 
# 2 1 0 1 2 0

R Solutions


Solution 1 - R

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 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChristopher DuBoisView Question on Stackoverflow
Solution 1 - RrcsView Answer on Stackoverflow