在 table() 的结果中包含零计数级别 [英] Include levels of zero count in result of table()
本文介绍了在 table() 的结果中包含零计数级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个向量y",我使用 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
但是,我还希望结果包含有零个 2 和零个 5 的事实.我可以为此使用 table()
吗?
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?
想要的结果:
# 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屋!
查看全文