Include levels of zero count in result of table()

好久不见. 提交于 2019-11-26 00:55:29

问题


I have a vector of integers between 0 and 5. I want to compute a histogram of counts. For example:

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

However, I also want the results to include the fact that there are zero 2\'s and zero 5\'s, ie. I want the returned vector to have length 6. Can I use table() for this?

Desired result:

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

回答1:


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 


来源:https://stackoverflow.com/questions/1617061/include-levels-of-zero-count-in-result-of-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!