在table()的结果中包括零计数级别 [英] Include levels of zero count in result of table()

查看:75
本文介绍了在table()的结果中包括零计数级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个0到5之间的整数向量.我想计算计数的直方图.例如:

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 

但是,我也希望结果包括一个事实,即零2和零5.我希望返回的向量长度为​​6.我可以为此使用table()吗?

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?

所需结果:

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

推荐答案

将变量转换为factor,并使用levels设置要包括在结果中的类别.计数为零的值也将出现在结果中:

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 

这篇关于在table()的结果中包括零计数级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆