Raivo,
Thanks for that tip! I knew there must be a simple way to accomplish
this... It works quite well now. FYI, if others are interested in
accomplishing a similar task (boxplots per person), I've included the
function below.
Michael
-----
iBoxplots <- function(dataset, dv, idvar, numPerPlot=10, facetby=NULL,
pdfFile=NULL, useLattice=FALSE) {
require(lattice)
require(ggplot2)
noMissing <- na.omit(dataset)
#plot numPerPlot at a time
numplots <- ceiling(length(unique(noMissing[[idvar]]))/numPerPlot)
idList <- unique(noMissing[[idvar]])
#iterate through each plot
if (!missing(pdfFile) && is.character(pdfFile)) pdf(file=pdfFile)
for (i in 1:numplots) {
workingIds <- idList[((i-1)*numPerPlot+1):min((i*numPerPlot),
length(idList))]
workingSubset <- noMissing[noMissing[[idvar]] %in% workingIds,]
#ensure that id is coded as a factor (trying to do this on the
whole dataset once doesn't make sense because factor levels change per
subset)
workingSubset[[idvar]] <- factor(workingSubset[[idvar]])
#only open a new window if we aren't printing to file
if (missing(pdfFile))
dev.new()
if (missing(facetby)) {
if (useLattice) {
latFormula <- as.formula(paste(idvar, "~", dv))
print(bwplot(latFormula, workingSubset))
}
else {
print(ggplot(workingSubset, aes_string(x=idvar, y=dv)) +
geom_boxplot() + coord_flip())
}
}
else {
#determine the number of levels of the facetby var, then plot
across columns (could get ugly)
dataset[[facetby]] <- factor(dataset[[facetby]])
numlevels <- length(levels(dataset[[facetby]]))
if (useLattice) {
latFormula <- as.formula(paste(idvar, "~", dv, "|", facetby))
print(bwplot(latFormula, workingSubset, layout=c(numlevels,
1)))
}
else {
facetformula <- as.formula(paste(". ~ ", facetby))
print(ggplot(workingSubset, aes_string(x=idvar, y=dv)) +
geom_boxplot() + coord_flip() + facet_grid(facetformula))
}
}
}
if (!missing(pdfFile) && is.character(pdfFile)) dev.off()
}
#example call: iBoxplots(exampleData, "reactionTime", "id",
numPerPlot=20, facetby="congruence", pdfFile="indivBoxplots.pdf")