如何在 R 中创建一个频率表,其中包含不可用值的零频率?
当我们在 R 中使用表函数时,输出显示向量或数据框列中可用值的频率。如果我们想为不属于向量或列的值创建频率为零的表,那么首先我们需要先将它们转换为因子,然后使用 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)
x11 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)
x21 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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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)
x50 1 2 3 4 5 6 7 8 9 10
144 104 0 0 0 129 0 0 0 0 123
以上是 如何在 R 中创建一个频率表,其中包含不可用值的零频率? 的全部内容, 来源链接: utcz.com/z/360312.html