如何为R中的lm中的有序分类变量获取0-1假人?

如何为R中的lm中的有序分类变量获取0-1假人?,r,lm,categorical-data,R,Lm,Categorical Data,当在R中使用分类因变量运行线性模型时,该变量在内部重新编码为虚拟变量: unord <- data.frame(y = c(1, 2, 3, 12, 11, 13, 101, 103, 102, 1003, 1002, 1001), cat = factor(rep(LETTERS[1:4], each = 3), ordered = FALSE)) model.matrix(lm(y~cat, data = unord)) (Intercept) cat

当在
R
中使用分类因变量运行线性模型时,该变量在内部重新编码为虚拟变量:

unord <- data.frame(y = c(1, 2, 3, 12, 11, 13, 101, 103, 102, 1003, 1002, 1001),
             cat = factor(rep(LETTERS[1:4], each = 3), ordered = FALSE))
model.matrix(lm(y~cat, data = unord))

   (Intercept) catB catC catD
1            1    0    0    0
2            1    0    0    0
3            1    0    0    0
4            1    1    0    0
5            1    1    0    0
6            1    1    0    0
7            1    0    1    0
8            1    0    1    0
9            1    0    1    0
10           1    0    0    1
11           1    0    0    1
12           1    0    0    1

unord您可以在
lm
中或在
model.matrix
中使用
contrasts
参数强制使用哪个对比度(因为我删除了额外的
lm
调用)

如果有多个因子列,则可以执行以下操作

nms <- names(ord)[sapply(ord, is.factor)] # get names of factor variables
model.matrix(y ~ cat, data = ord, 
                contrasts = sapply(nms, function(x) list(contr.treatment)))

nms当您将结果保存在一个数据框中时,例如
a
,那么您可以执行
因子(a$cat.L,levels=unique(a$cat.L),labels=1:length(unique(a$cat.L))
@Jimbou,
a$cat.L
NULL
。@Jimbou
broom::tidy(model.matrix(lm(y~cat,data=ord)))
提供了与
model.matrix(lm(y~cat,data=ord))相同的假人。
对不起,试试这个
a这是你想要的吗,或者
model.matrix(lm(y~因子(cat,ordered=FALSE),data=ord))
或者
model.matrix(lm(y~cat,data=order,contrasts=list(cat=control.treatment))
model.matrix(y ~ cat, data = ord, contrasts = list(cat=contr.treatment))
nms <- names(ord)[sapply(ord, is.factor)] # get names of factor variables
model.matrix(y ~ cat, data = ord, 
                contrasts = sapply(nms, function(x) list(contr.treatment)))