2
$\begingroup$

I have a factor with eight levels but have only have five comparisons I want to make. I create a matrix with all of the relevant contrasts, however, I need to invert this matrix prior to passing it to the contrasts() function in order to generate correct estimates. Given that I need a square matrix, is it possible to auto-generate two more orthogonal contrasts so that the Estimates returned by summary() are correct?

http://rstudio-pubs-static.s3.amazonaws.com/65059_586f394d8eb84f84b1baaf56ffb6b47f.html (See sections "DIY Contrasts" and "Running Fewer than J-1 Contrasts for J Groups")

Reproducible example below. Note: the model doesn't make much sense with the CO2 dataset, but the contrasts are exactly the ones I need to make for my original dataset.

# Use CO2 dataset for example
data<-CO2
# Only need eight levels
data<-data[data$Plant %in% levels(data$Plant)[1:8],] 
data$Plant<-factor(data$Plant)
levels(data$Plant)

# Set up contrasts
contrasts(data$Plant) <- 
  solve( t( cbind( 
    c(1,1,1,1), # Filler
    c(-0.5,0,1,0,-0.5,0,0,0), 
    c(-0.5,0.5,0,0, -0.5, 0.5, 0, 0),
    c(-0.5,0,0,1, -0.5, 0, 0, 0),  
    c(0,-0.5,0,-0.5, 0, 0.5, 0, 0.5),
    c(-0.5,0,-0.5, 0, 0.5, 0, 0.5,0)) ) 
  ) [,2:6] #Drop filler

# Run model
fit<-lm(uptake~Plant, data=data)
summary(fit)

Thank you, Egor

$\endgroup$
2
$\begingroup$

As the matrix is not square you have to compute the generalized inverse. You can simply substitute solve() with MASS::ginv(). R automatically adds some orthogonal contrasts to fill in the missing columns of the contrast matrix:

contrasts(data$Plant) <- 
  MASS::ginv( t( cbind( 
    c(1,1,1,1), # Filler
    c(-0.5,0,1,0,-0.5,0,0,0), 
    c(-0.5,0.5,0,0, -0.5, 0.5, 0, 0),
    c(-0.5,0,0,1, -0.5, 0, 0, 0),  
    c(0,-0.5,0,-0.5, 0, 0.5, 0, 0.5),
    c(-0.5,0,-0.5, 0, 0.5, 0, 0.5,0)) ) 
  ) [, 2:6]

However, you don't need the filler at all if you compute the generalized inverse. I provide some details in my answer here.

contrasts(data$Plant) <- 
  MASS::ginv( rbind( 
    c(-0.5,0,1,0,-0.5,0,0,0), 
    c(-0.5,0.5,0,0, -0.5, 0.5, 0, 0),
    c(-0.5,0,0,1, -0.5, 0, 0, 0),  
    c(0,-0.5,0,-0.5, 0, 0.5, 0, 0.5),
    c(-0.5,0,-0.5, 0, 0.5, 0, 0.5,0) ) 
  )
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.