繁体   English   中英

R:如何将有序因子转换为虚拟变量?

[英]R: How can I convert an ordered factor to dummy variables?

例如。 有序水平的一个因素

[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这样的函数,但是model.matrix解决方案。

这似乎起作用。

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

如果你的目的是创建一个自定义的对比矩阵的变量,并在你的情况下,它看起来像你正在创建作为描述的累积编码序变量在这里 ,你可以做以下。

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)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM