R 程序创建与女性身高数据集对应的因子


2023年2月9日, Learn eTutorial
1338

如何创建与女性身高数据集对应的因子

在这里,我们将解释如何编写 R 程序来创建与女性身高数据集对应的因子。我们在这里使用内置函数 cut() 进行创建。函数 cut() 将 x 的范围分成区间。它根据区间对 x 中的值进行编码。这些函数的语法是


cut(x, …) #Where x is an R object,like matrix, array or data frame
 

如何在 R 程序中创建与女性身高数据集对应的因子

以下是在 R 程序中创建与女性身高数据集对应的因子所使用的步骤,我们直接将值赋给内置函数。并打印函数结果。这里我们使用变量 D 来赋值女性数据变量 H 来使用 cut() 方法赋值计算出的因子值。打印结果因子。

算法

步骤 1:将变量 D 赋值为给定数据

步骤 2:首先打印原始数据

步骤 3:调用内置函数 cut,如 cut(women$height,3)

步骤 4:将变量 H 赋值为函数结果

步骤 5:打印结果因子

 

R 源代码

                                          D= women
print("Women data set of height and weights:")
print(D)
H = cut(women$height,3)
print("Factor corresponding to height:")
print(table(H))
                                      

输出

[1] "Women data set of height and weights:"
   height weight
1      58    115
2      59    117
3      60    120
4      61    123
5      62    126
6      63    129
7      64    132
8      65    135
9      66    139
10     67    142
11     68    146
12     69    150
13     70    154
14     71    159
15     72    164
[1] "Factor corresponding to height:"
height_f
  (58,62.7] (62.7,67.3]   (67.3,72] 
          5           5           5