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

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

问题描述

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

解决方案

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天全站免登陆