67

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
Henrik
  • 65,555
  • 14
  • 143
  • 159
Christopher DuBois
  • 42,350
  • 23
  • 71
  • 93

1 Answers1

91

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 
Henrik
  • 65,555
  • 14
  • 143
  • 159
rcs
  • 67,191
  • 22
  • 172
  • 153
  • Hi. Thanks for your answer. What if the levels are string factors? – SteveMcManaman Aug 26 '21 at 07:53
  • @SteveMcManaman The same thing: `y <- c("A","A","B","D","E","E");` `table(factor(y,levels=c("A","B","C","D","E","F")))` will produce a similar result – Henry Jun 18 '22 at 00:13