Skip to content

Instantly share code, notes, and snippets.

@aammd
Created December 3, 2013 22:42
Show Gist options
  • Save aammd/7778916 to your computer and use it in GitHub Desktop.
Save aammd/7778916 to your computer and use it in GitHub Desktop.
A demonstration of how you can use ordered contrasts when your hypothesis involves the an *ordinal* response to factor levels. i.e. when your factor levels can be placed in a sequence based on their predicted effect: low<med<high
## a demonstration of ordered contrasts
## three levels, A, B, and C
factor1 <- rep(LETTERS[1:3],c(15,15,15))
## Another factor
factor2 <- rep(letters[1:3],15)
## check combinations
table(factor1,factor2)
testdata <- data.frame(factor1,factor2)
head(testdata)
## a response that varies with each of these factors:
fact1effect <- c(20,30,40) # 10 between each level
fact2effect <- c(5,10,15) # 5 between each level
## let's have a response which is a linear combination of the factor effects, plus noise:
testdata$resp <- with(testdata,fact1effect[factor1]+fact2effect[factor2]+rnorm(n=45,mean=0,sd=1))
testdata$combo <- with(testdata,paste0(factor1,factor2))
library(ggplot2)
foo <- ggplot(testdata,aes(factor1,resp,colour=factor2))+geom_boxplot(position = "dodge")
foo
## both factor1 and factor2 have positive effects on resp. this is the hypothesis we had always meant to test!
testdata$factor1ord <- ordered(x=factor1,levels=c("A","B","C")) ## order the factor
testdata$factor2ord <- ordered(x=factor2,levels=c("a","b","c")) ## order the factor
## all the following model tells us is that some factor levels are different
unorderedmodel <- lm(resp~factor1*factor2,data=testdata)
summary(unorderedmodel) ## contrasts between factor levels
## the ordered contrasts show us that each factor has a linear effect on the response
orderedmodel <- lm(resp~factor1ord*factor2ord,data=testdata)
summary(orderedmodel) ## contrasts between factor levels
## the lack of interactions is expected, since we *KNOW* that the factors are additive
## the contrasts come out close to the original differences of the factor levels: 13 +- 0.2 for factor1 (actually 10)
## and 7 +- 0.22 for factor2 (actually 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment