[英]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.