Lab Exercise for R: Reapeated Measures

Exercise 1: Read the file and stack data if they are in column format

Define function make.rm()

> make.rm<-function(constant,repeated,data,contrasts) {
  if(!missing(constant) && is.vector(constant)) {
   if(!missing(repeated) && is.vector(repeated)) {
    if(!missing(data)) {
     dd<-dim(data)
     replen<-length(repeated)
     if(missing(contrasts))
      contrasts<-
       ordered(sapply(paste("T",1:length(repeated),sep=""),rep,dd[1]))
     else
      contrasts<-matrix(sapply(contrasts,rep,dd[1]),ncol=dim(contrasts)[2])
     if(length(constant) == 1) cons.col<-rep(data[,constant],replen)
     else cons.col<-lapply(data[,constant],rep,replen)
     new.df<-data.frame(cons.col,
      repdat=as.vector(data.matrix(data[,repeated])),
      contrasts)
     return(new.df)
    }
   }
  }
  cat("Usage: make.rm(constant, repeated, data [, contrasts])\n")
  cat("\tWhere 'constant' is a vector of indices of non-repeated data and\n")
  cat("\t'repeated' is a vector of indices of the repeated measures data.\n")
  }

You can now use the make.rm function to reformat your data from column to stacked format. Read a data file that contains repeated measures as multiple columns

> groceries = read.table("http://ww2.coastal.edu/kingw/statistics/R-tutorials/text/groceries.txt", header=T)
> groceries

> groceries.stacked <- make.rm(constant="subject", repeated=c("storeA","storeB","storeC","storeD"), data=groceries)
> groceries.stacked

Exercise 2: Repeated measures ANOVA

Set more intuitive column names and construct the ANOVA model for store and product nested within store

> colnames(groceries.stacked) = c("product","price","store")
> aov.out = aov(price ~ store + Error(product/store), data=groceries.stacked)
> summary(aov.out)


last modified: 4/21/15