【问题标题】:How to convert all numeric columns to intervals in R [duplicate]如何将所有数字列转换为 R 中的间隔[重复]
【发布时间】: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))

标签: r dataframe c5.0


【解决方案1】:

您可以使用 dplyr 包中的 mutate(across()),将 cut()breaks=5 应用于每个数字列:

mutate(df, across(where(is.numeric),cut,breaks=5))

输出:

      tenureType localityType monthlyRent
1 Full ownership        Rural   (156,292]
2 Full ownership        Urban  (19.3,156]
3 Full ownership         Camp   (428,564]
4       For free        Urban  (19.3,156]
5 Full ownership         Camp   (564,701]
6       For free         Camp  (19.3,156]

输入

df = structure(list(tenureType = c("Full ownership", "Full ownership", 
                              "Full ownership", "For free", "Full ownership", "For free"), 
               localityType = c("Rural", "Urban", "Camp", "Urban", "Camp", 
                                "Camp"), monthlyRent = c(200L, 140L, 500L, 100L, 700L, 20L
                                )), row.names = c(NA, -6L), class = "data.frame")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-25
    • 2023-03-14
    • 2020-11-08
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 2022-01-10
    • 2021-04-05
    相关资源
    最近更新 更多