。與排序的等級R:如何將有序因子轉換爲虛擬變量?例如,
[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:如何將有序因子轉換爲虛擬變量?例如,
[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
,但不能得到解決。
這似乎工作。
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
如果你的目的是創建一個自定義的對比矩陣的變量,並在你的情況下,它看起來像你正在創建一個累積編碼序變量描述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)
這種「自定義」的變量可以直接在其它功能(例如,迴歸方程),而不需要手動創建虛擬變量被使用。
看看這個問題的答案:https://stackoverflow.com/questions/38678378/factor-levels-default-to-1-and-2-in-r-dummy-variable?rq = 1 –