Anova.prepare = function(dframe, code) { # Funtion to convert a data frame consisting # of one or more dependent variables, a subjects # factor, at least one within-subjects factor(s) # and zero or more between subjects factors into # a form that can be used by Anova() in library(car) # dframe: # code: a vector consisting obligatorily of "s" (subject) # "w" (within) and "d" (dependent variable(s)) and # optionally "b" (between) to identify the columns in dframe # as one of "d", "s", "w", "b". subj = dframe[,code=="s"] o = w = dframe[,code=="w"] if(any(code=="b")) { b.nm = names(dframe)[code=="b"] b = as.matrix(dframe[,code=="b"]) } dep = as.matrix(dframe[,code=="d"]) if(!is.null(dim(o)) ) { for(j in 1:ncol(o)){ if(j == 1) k = as.numeric(o[,j]) else k = paste(k, as.numeric(o[,j]), sep=".") } } else { k = as.numeric(o) nm = names(dframe)[code=="w"] } temp = subj == unique(subj)[1] p = sort(k[temp]) subjorder = match(p, k[temp]) subjorder.rep = rep(subjorder, ncol(dep)) if(!is.null(dim(o)) ) { subjwithin = w[temp,] subjwithin = subjwithin[subjorder.rep,] } else { subjwithin = w[temp] subjwithin = data.frame(subjwithin[subjorder.rep]) names(subjwithin) = nm } omat = NULL subj = as.character(subj) for(j in unique(subj)){ temp = subj == j subjdep = as.matrix(dep[temp,]) subjdep = subjdep[subjorder,] subjdep = c(subjdep) if(any(code=="b")) { subjbet = as.matrix(b[temp,]) subjbet = apply(subjbet, 2, unique) omat$b = rbind(omat$b, subjbet) } omat$d = rbind(omat$d, subjdep) omat$subj = c(omat$subj, j) } if(any(code=="b")) rownames(omat$d) = rownames(omat$b) = omat$subj else rownames(omat$d) = omat$subj omat$w = subjwithin if(any(code == "b")) { if(ncol(omat$b)==1) colnames(omat$b) = b.nm } omat }