我有一个公式和一个数据框,我想提取model.matrix().但是,我需要生成的矩阵包含在原始数据集中找到的NA.如果我model.frame()这样做,我会简单地通过它na.action=NULL.但是,我需要的输出是model.matrix()格式.具体来说,我只需要右侧变量,我需要输出为矩阵(不是数据帧),我需要将因子转换为一系列虚拟变量.
我确信我可以使用循环或其他东西一起破解某些东西,但我想知道是否有人可以建议更清洁,更有效的解决方法.非常感谢你的时间!
这是一个例子:
dat <- data.frame(matrix(rnorm(20),5,4), gl(5,2))
dat[3,5] <- NA
names(dat) <- c(letters[1:4], 'fact')
ff <- a ~ b + fact
# This omits the row with a missing observation on the factor
model.matrix(ff, dat)
# This keeps the NA, but it gives me a data frame and does not dichotomize the factor
model.frame(ff, dat, na.action=NULL)
Run Code Online (Sandbox Code Playgroud)
这是我想要获得的:
(Intercept) b fact2 fact3 fact4 fact5
1 1 0.7266086 0 0 0 0
2 1 …Run Code Online (Sandbox Code Playgroud)