设置model.matrix中部分因素的对比

时间:2017-04-12 04:47:27

标签: r lm model.matrix

我有一个实验设计,我想要拟合线性回归模型。

这是设计data.frame

design.df <- data.frame(batch=rep(c(1:3,1:3),4),
                      species=rep(c(rep("mouse",3),rep("rat",3)),4),
                      sex=rep(c(rep("M",12),rep("F",12))),
                      stringsAsFactors = F)

design.df$speciesdesign.df$sex都是factors

design.df$species <- factor(design.df$species,levels=c("mouse","rat"))
design.df$sex <- factor(design.df$sex,levels=c("F","M"))

design.df$species的对比度编码应为contr.treatment,而design.df$sex的对比度编码应为contr.sum

要把它设置为model.matrix,我想也许这可行:

contrasts.list <- list(batch=NA,species="contr.treatment",sex="contr.sum")

design.mat <- model.matrix(as.formula(paste0("~",paste(model.factors,collapse="+"))),contrasts=contrasts.list,data=design.df)

显然根据我得到的错误它不起作用:

Error in `contrasts<-`(`*tmp*`, value = contrasts.arg[[nn]]) : 
  contrasts apply only to factors

所以我的问题是如何根据我指定的model.matrixdesign.df获取contrasts.list

1 个答案:

答案 0 :(得分:1)

您正在使用未在任何地方定义的变量model.factors。不确定目标是什么。如果您只想将所有这些值作为协变量,则可以执行

contrasts.list <- list(species="contr.treatment", sex="contr.sum")
design.mat <- model.matrix(~., contrasts=contrasts.list, data=design.df)

请注意,您的contrasts.list应该只包含因子变量的值。不要包含batch