简体   繁体   中英

changing the base/reference for a design matrix model.matrix

I have a dataframe which looks like this:

    df <- data.frame(id= rep(seq(1:125),3),
  timpoint= c(rep("T1", 125), rep("T2", 125), rep("T3", 125)),
                 treatment=c(rep("A",25),rep("B",25),rep("C",25),rep("D",25),rep("E",25)))
interaction.col <- paste(df$timpoint, df$treatment, sep = "_")  

df <- cbind(df, interaction.col)

and I have generated a desgin matrix as follows:

model.matrix(~treatment:timpoint, df, list(treatment = contr.sum, timpoint=contr.treatment))

For the treatment:timepoint effect, my last group is set as reference. I'd like to change this for instance to group "C" and for some reason relevel doesn't work.

I also tried setting a base:

model.matrix(~treatment:timpoint, df, list(treatment = contr.sum, timpoint=contr.treatment), base="C")

How can i change the basis for timepoint to "T1" and for the interaction effect (treatment:timepoint) to for instance group "C"?

If you code your treatment variable as a factor you can relevel the factor and then re-run the model matrix:

df <- data.frame(
    id = rep(1:125, 3),
    timpoint = paste0("T", rep(1:3, each=125)),
    treatment = gl(5, 25, labels = LETTERS[1:5]))
interaction.col <- paste(df$timpoint, df$treatment, sep = "_")  
df <- cbind(df, interaction.col)
model.matrix(~treatment:timpoint, df)
df$treatment <- relevel(df$treatment, "C")
model.matrix(~treatment:timpoint, df)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM