如何为 R 数据框列中的值范围创建频率表?

要为 R 数据框列中的值范围创建频率表,我们可以按照以下步骤操作 -

  • 首先,创建一个数据框。

  • 然后,使用表函数和切割函数来创建值范围的频率表。

示例 1

创建数据框

让我们创建一个数据框,如下所示 -

x<-sample(1:10,20,replace=TRUE)
df1<-data.frame(x)
df1

执行时,上述脚本生成以下内容output(this output will vary on your system due to randomization)-

  x
1 2
2 10
3 8
4 5
5 5
6 2
7 8
8 3
9 5
10 9
11 4
12 10
13 3
14 2
15 7
16 5
17 9
18 9
19 6
20 7

创建值范围的频率表

使用 table 函数和 cut 函数为值范围创建一个频率表,例如 1 到 11,使用数据框 df1 的 x 列 -

x<-sample(1:10,20,replace=TRUE)
df1<-data.frame(x)
table(cut(df1$x,breaks=seq.int(from=1,to=11,by=2)))

输出

(1,3] (3,5] (5,7] (7,9] (9,11]
  5     5     3     5      2

示例 2

创建数据框

让我们创建一个数据框,如下所示 -

y<-round(rnorm(20),1)
df2<-data.frame(y)
df2

执行时,上述脚本生成以下内容output(this output will vary on your system due to randomization)-

   y
1 0.2
2 1.0
3 0.4
4 0.5
5 -1.4
6 -0.9
7 1.2
8 -0.8
9 -0.6
10 -0.1
11 -0.1
12 0.5
13 -1.3
14 0.3
15 -1.9
16 0.9
17 -1.6
18 1.0
19 -0.3
20 0.0

创建值范围的频率表

使用 table 函数和 cut 函数为值范围创建一个频率表,例如 -2 到 1.5,使用数据框 df2 的 y 列 -

y<-round(rnorm(20),1)
df2<-data.frame(y)
table(cut(df2$y,breaks=seq.int(from=-2,to=1.5,by=0.5)))

输出

(-2,-1.5] (-1.5,-1] (-1,-0.5] (-0.5,0] (0,0.5] (0.5,1] (1,1.5]
   2          2          3       4       5       3       1