dan
dan

Reputation: 6314

Setting contrasts for part of the factors in a model.matrix

I have an experimental design to which I'd like to fit a linear regression model.

Here's the design 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$species and design.df$sex are both factors:

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

The contrast encoding of design.df$species should be contr.treatment whereas that of design.df$sex should be contr.sum.

To set it it as a model.matrix I thought perhaps this could work:

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)

Obviously it doesn't work according to the error I get:

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

So my question is how do I get the model.matrix from design.df according to the contrasts.list I specify?

Upvotes: 1

Views: 1093

Answers (1)

MrFlick
MrFlick

Reputation: 206546

You are using a variable model.factors that's not defined anywhere. Not sure what the goal is. If you just wanted all these values as covariates, you can do

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

Note that your contrasts.list should only have values for the factor variables. Do not include batch.

Upvotes: 1

Related Questions