为了对数据集中的因子变量进行一次热编码,我在这篇文章中使用了用户“Ben”的强大功能:如何使用 data.table 对因子变量进行一次热编码?
one_hot <- function(dt, cols="auto", dropCols=TRUE, dropUnusedLevels=FALSE){
# One-Hot-Encode unordered factors in a data.table
# If cols = "auto", each unordered factor column in dt will be encoded. (Or specifcy a vector of column names to encode)
# If dropCols=TRUE, the original factor columns are dropped
# If dropUnusedLevels = TRUE, unused factor levels are dropped
# Automatically get the unordered factor columns
if(cols[1] == "auto") cols <- colnames(dt)[which(sapply(dt, function(x) is.factor(x) & !is.ordered(x)))]
# Build tempDT containing and ID column and 'cols' columns
tempDT <- dt[, cols, with=FALSE]
tempDT[, ID := .I]
setcolorder(tempDT, unique(c("ID", colnames(tempDT))))
for(col in cols) set(tempDT, j=col, value=factor(paste(col, tempDT[[col]], sep="_"), levels=paste(col, levels(tempDT[[col]]), sep="_")))
# One-hot-encode
if(dropUnusedLevels == TRUE){
newCols <- dcast(melt(tempDT, id = 'ID', value.factor = T), ID ~ value, drop = T, fun = length)
} else{
newCols <- dcast(melt(tempDT, id = 'ID', value.factor = T), ID ~ value, drop = F, fun = length)
}
# Combine binarized columns with the original dataset
result <- cbind(dt, newCols[, !"ID"])
# If dropCols = TRUE, remove the original factor columns
if(dropCols == TRUE){
result <- result[, !cols, with=FALSE]
}
return(result)
}
该函数为每个因子列的所有 n 个因子水平创建 n 个虚拟变量。但由于我想使用数据进行建模,所以每个因子列只需要 n-1 个虚拟变量。这是可能的,如果是的话,我该如何使用这个功能来做到这一点?
从我的角度来看,这条线必须调整:
newCols <- dcast(melt(tempDT, id = 'ID', value.factor = T), ID ~ value, drop = T, fun = length)
这是输入表...
ID color size
1: 1 black large
2: 2 green medium
3: 3 red small
library(data.table)
DT = setDT(structure(list(ID = 1:3, color = c("black", "green", "red"),
size = c("large", "medium", "small")), .Names = c("ID", "color",
"size"), row.names = c(NA, -3L), class = "data.frame"))
...以及所需的输出表:
ID color.black color.green size.large size.medium
1 1 0 1 0
2 0 1 0 1
3 0 0 0 0