【问题标题】:Convert continuous variables to binary variables将连续变量转换为二进制变量
【发布时间】:2018-09-16 21:36:03
【问题描述】:

我正在尝试使用cut 函数将连续变量转换为 R 中分类变量的二进制列。代码是

    xyz=rnorm(20,3,1)
    xcut=cut(xyz,breaks=c(2,3))

这会将xyz 转换为分类变量,但我想要三个二进制列,其中列名为“3”,如果xyz[1] 为 1.5,那么第一行的值是 1、0 和 0,对于xyz 的所有 20 个值,我都需要它。我不想使用 for 和 if 循环来创建这个 20x3 矩阵,我已经可以用 xyz 以数字方式完成它。我想知道是否有更短的方法可以做到这一点?

【问题讨论】:

  • 我倾向于在这里使用model.matrixmodel.matrix(~0 + xcut)

标签: r binary cut categorical-data


【解决方案1】:

我们可以使用table

xcut <- cut(xyz,breaks=c(-Inf,2,3, Inf), labels = c("<2", "2-3", ">3"))
table(seq_along(xcut), xcut)

数据

set.seed(24)
xyz <- rnorm(20,3,1)

【讨论】:

    【解决方案2】:

    其中一种解决方案是使用无监督离散化。它完全基于观察到的连续属性的分布。以下是 2 个函数的用法示例:

    # 1. Functions
    
    # 1.1. Equal-width discretization for a single attribute
    disc_width <- function(v, k = 5) {
      w <- diff(r <- range(v)) / k
      c(r[1], seq(r[1] + w, r[2] - w, w), r[2])
    }
    
    # 1.2. Equal-frequency discretization for a single attribute
    disc_freq <- function(v, k = 5) {
      v <- v[!is.na(v)]
      r <- range(v)
      f <- unique(quantile(v, seq(1/k, 1-1/k, 1/k))) 
      c(r[1], f, r[2])
    }
    
    # 2. Usage
    
    # 2.1. Feature
    x <- mtcars$mpg
    
    # 2.2. Range of feature 'x'
    range(x)
    
    # 2.3. Equal-width discretization
    disc_width(x, 4)
    
    # 2.4. Equal-frequency discretization
    disc_freq(x, 5)
    

    【讨论】:

      猜你喜欢
      • 2023-02-20
      • 1970-01-01
      • 1970-01-01
      • 2018-03-17
      • 2019-11-24
      • 2018-05-18
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多