Include levels of zero count in result of table()

前端 未结 1 898
孤街浪徒
孤街浪徒 2020-11-22 16:50

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 
1条回答
  •  心在旅途
    2020-11-22 17:20

    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 
    

    0 讨论(0)
提交回复
热议问题