我有一个data.frame数字和因子变量组成,如下所示.
testFrame <- data.frame(First=sample(1:10, 20, replace=T),
Second=sample(1:20, 20, replace=T), Third=sample(1:10, 20, replace=T),
Fourth=rep(c("Alice","Bob","Charlie","David"), 5),
Fifth=rep(c("Edward","Frank","Georgia","Hank","Isaac"),4))
Run Code Online (Sandbox Code Playgroud)
我想构建一个matrix为该因子分配虚拟变量并单独保留数值变量.
model.matrix(~ First + Second + Third + Fourth + Fifth, data=testFrame)
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,在运行时会将lm每个因子的一个级别作为参考级别.但是,我想为matrix所有因素的每个级别构建一个带有虚拟/指示变量的变量.我正在建立这个矩阵,glmnet所以我不担心多重共线性.
有没有办法model.matrix为每个级别的因子创建假人?
我正在研究一个预测问题,我在R中构建一个决策树,我有几个分类变量,我想在我的训练和测试集中对它们进行一次性热编码.我设法用我的训练数据做到:
temps <- X_train
tt <- subset(temps, select = -output)
oh <- data.frame(model.matrix(~ . -1, tt), CLASS = temps$output)
Run Code Online (Sandbox Code Playgroud)
但我找不到在我的测试集上应用相同编码的方法,我该怎么做?