如何在R中创建一个频数表,其中包含不存在值的零频数?
当我们在R中使用table函数时,输出显示向量或数据框列中可用值的频率。如果我们想创建包含不存在于向量或列中的值的零频率的表,那么首先需要将它们转换为因子,然后使用table函数。
示例1
x1<−c(1,1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,4,4,4,4,6,6) x1<−factor(x1,levels=c(1:6)) table(x1)
输出
x1 1 2 3 4 5 6 7 5 4 4 0 2
示例2
x2<−sample(c(1,2,3,5,6,7),200,replace=TRUE) x2
输出
[1] 2 3 1 7 7 2 3 5 5 3 1 3 7 6 7 2 6 3 2 1 1 1 5 7 3 6 6 5 5 5 5 2 2 7 7 6 3 [38] 7 1 6 2 7 3 6 5 2 6 7 7 2 3 1 3 3 7 1 1 5 7 5 3 1 6 2 3 1 2 5 3 3 1 3 7 2 [75] 1 6 2 1 6 7 7 2 1 3 7 6 7 6 3 5 6 7 7 7 3 3 2 6 2 1 3 7 6 1 3 5 5 3 7 1 3 [112] 2 1 2 3 1 3 6 3 3 5 3 2 2 7 7 6 3 2 2 3 5 3 7 6 6 6 6 2 7 1 7 7 5 3 6 5 3 [149] 5 1 6 2 5 5 1 6 3 6 3 6 5 5 1 1 6 3 3 7 2 3 5 3 1 1 7 1 3 2 3 3 7 7 7 3 5 [186] 1 3 7 6 7 5 3 6 3 6 1 1 1 3 7
示例
x2<−factor(x2,levels=c(1:7)) table(x2)
输出
x2 1 2 3 4 5 6 7 32 26 48 0 26 31 37
示例3
x3<−sample(c(0,1,2,4,5,6),500,replace=TRUE) x3
输出
[1] 5 4 4 6 6 4 2 2 5 0 1 1 1 1 0 2 2 1 0 1 5 2 4 5 0 5 4 2 5 2 6 0 1 6 4 2 4 [38] 6 0 6 2 6 5 1 6 0 0 2 4 2 4 5 4 4 0 1 5 1 5 6 4 2 5 4 5 6 0 2 1 1 2 4 5 2 [75] 6 0 4 0 5 5 0 2 5 6 1 5 6 2 6 2 0 0 1 6 2 2 5 6 1 5 5 6 1 1 6 5 1 6 5 2 2 [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(0,1,5,10),500,replace=TRUE) x5
输出
[1] 1 0 1 0 5 5 10 0 0 1 10 0 0 5 10 1 5 1 10 0 1 0 1 5 1 [26] 5 10 5 10 1 10 1 0 1 1 0 5 5 5 0 10 5 10 5 5 0 5 0 0 1 [51] 0 5 5 0 1 10 10 0 0 1 0 0 0 10 5 0 1 1 0 0 5 10 0 5 1 [76] 10 10 5 1 1 0 0 0 0 0 5 5 0 10 0 10 0 5 0 10 5 0 1 1 5 [101] 0 1 5 1 1 0 0 5 1 10 0 10 5 5 0 1 5 0 10 1 10 10 0 10 0 [126] 5 0 10 5 5 10 10 10 10 10 5 0 5 0 0 0 5 0 10 0 10 5 10 1 0 [151] 10 5 0 10 10 0 5 10 0 0 0 5 5 0 1 5 5 1 5 5 0 10 10 10 1 [176] 0 5 0 0 10 5 5 0 10 10 5 10 0 1 1 1 1 0 0 10 10 1 10 1 5 [201] 1 0 5 10 10 10 1 10 5 5 0 5 10 5 1 5 5 10 5 1 1 0 0 10 0 [226] 0 5 1 1 0 0 1 5 0 10 1 5 0 0 1 10 1 5 0 5 0 5 1 0 5 [251] 1 10 5 0 5 0 1 5 1 1 10 5 10 0 5 0 1 0 0 5 0 5 1 10 10 [276] 0 0 0 10 0 1 5 10 5 5 0 5 5 0 1 5 0 10 1 0 5 1 0 5 0 [301] 1 5 5 1 1 0 10 0 10 10 10 5 10 0 10 5 5 0 5 10 0 10 5 10 5 [326] 0 10 1 0 1 0 1 1 5 1 10 5 0 5 5 5 10 10 10 10 1 10 1 1 10 [351] 5 1 1 1 1 5 0 10 0 10 10 5 10 1 10 5 10 10 10 1 0 0 0 0 10 [376] 5 0 5 0 5 10 1 10 10 1 0 10 10 1 10 1 5 10 0 0 1 0 5 0 0 [401] 5 1 0 10 1 0 10 5 10 5 5 10 0 10 1 0 10 10 1 0 10 0 0 10 10 [426] 5 5 10 1 10 0 5 0 5 1 5 10 5 1 0 5 0 10 0 5 5 5 0 0 10 [451] 5 0 10 5 10 1 5 1 5 0 1 10 5 10 0 1 10 0 0 10 1 1 0 0 5 [476] 0 5 10 5 5 10 5 5 1 5 1 10 1 1 10 0 1 0 1 1 5 1 1 0 10
示例
x5<−factor(x5,levels=c(0:10)) table(x5)
输出
x5 0 1 2 3 4 5 6 7 8 9 10 144 104 0 0 0 129 0 0 0 0 123
广告