【问题标题】:R: How can I convert an ordered factor to dummy variables?R:如何将有序因子转换为虚拟变量?
【发布时间】:2017-08-15 10:31:06
【问题描述】:

例如。具有有序水平的因子

[1] 0 0 6 6 3 4 Levels: 0 < 1 < 2 < 3 < 4 < 5 < 6

应该转换成

ti0 ti1 ti2 ti3 ti4 ti5 ti6 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 0 0

我查看了 dummies 之类的包和模型 model.matrix 之类的函数,但无法找到解决方案。

【问题讨论】:

标签: r dummy-variable


【解决方案1】:

这似乎有效。

x <- factor(c("0", "0", "6", "6", "3", "4"), levels = 0:6, ordered = TRUE)

out <- matrix(0, nrow = length(x), ncol = max(as.numeric(x)))

for (i in 1:length(x)) {
  out[i, 1:as.numeric(x[i])] <- 1
}
colnames(out) <- paste("ti", levels(x), sep = "")


     ti0 ti1 ti2 ti3 ti4 ti5 ti6
[1,]   1   0   0   0   0   0   0
[2,]   1   0   0   0   0   0   0
[3,]   1   1   1   1   1   1   1
[4,]   1   1   1   1   1   1   1
[5,]   1   1   1   1   0   0   0
[6,]   1   1   1   1   1   0   0

【讨论】:

    【解决方案2】:

    如果您的目的是创建一个具有自定义对比矩阵的变量,并且在您的情况下,您似乎正在创建一个累积编码的序数变量,如 here 所述,您可以执行以下操作。

    x <- factor(c("0", "0", "6", "6", "3", "4"), levels = 0:6, ordered = TRUE)
    
    # Create custom contrast function
    contr.cum <- function(x, base = 1L) 
    {
      dmns <- levels(x)
      n <- length(dmns)
      contr <- array(diag(n), dim = c(n,n), dimnames = list(dmns, dmns))
      contr[lower.tri(contr)] <- 1
      contr <- contr[, -base, drop = FALSE]
      contr
    }
    
    # Apply custom function to variable
    contrasts(x) <- contr.cum(x)
    
    # View model matrix
    model.matrix(~x)
    

    此“自定义”变量可直接用于其他函数(例如回归方程),无需手动创建虚拟变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      • 2012-12-19
      • 1970-01-01
      相关资源
      最近更新 更多