【发布时间】:2023-02-13 07:37:51
【问题描述】:
我从 .sav 文件中读取了 840 列的数据框。我使用 data <- haven::as_factor(data) 将所有列转换为因子
这是一个例子: 读取文件后的数据,没有转换为因子:
| tenureType | localityType | monthlyRent |
|---|---|---|
| 1 | 1 | 200 |
| 1 | 2 | 140 |
| 1 | 3 | 500 |
| 2 | 2 | 100 |
| 1 | 3 | 700 |
| 2 | 3 | 20 |
--
在data <- haven::as_factor(data)之后
| tenureType | localityType | monthlyRent |
|---|---|---|
| Full ownership | Rural | 200 |
| Full ownership | Urban | 140 |
| Full ownership | Camp | 500 |
| For free | Urban | 100 |
| Full ownership | Camp | 700 |
| For free | Camp | 20 |
我必须将数据转换为其标签,因为我想对文本进行一些处理。
我想使用
C50库构建一个决策树,所以我想将所有列的值(作为因子)转换为数字(如 monthlyRent)为间隔因子我希望数据是这样的:
tenureType localityType monthlyRent Full ownership Rural 156-292 Full ownership Urban 20-156 Full ownership Camp 428 - 564 For free Urban 20-156 Full ownership Camp 564 - 700 For free Camp 20-156 我需要将每个数字列转换为 5 个类别
间隔计算方式:( max - min ) / 5在上面的示例中:(700 - 20 ) / 5 = 136 间隔为:[20-156]、[156-292]、[292-428]、[428-564]、[564-700]我有 840 列,所以我不知道列名,我希望间隔是动态的,因为这样的列范围是从 0 到 10,其他的范围是 0 - 10000
我想要最好的方法。
如果有比
( max - min ) / 5计算的间隔更好的方法,我将不胜感激
【问题讨论】:
-
您将如何为每个数字列选择间隔?也就是说,建议 0-210、210-600、600-900 是
monthlyRent的间隔集的信息在哪里? -
间隔只是一个例子,我不知道间隔是怎样的。但我希望它是动态的。我要求最好的方法
-
示例数据根本没有说明如何计算间隔。你有两个“完全所有权营地”,它们有不同的间隔。那是基于什么?
-
我已经编辑了问题并澄清了这一点。 @浪塘
-
你可以这样做:
library(dplyr); mutate(df, across(where(is.numeric),cut,breaks=5))