Skip to content

Labeling charts within a loop

2 messages · Doran, Harold, Peter Dalgaard

#
"Doran, Harold" <HDoran at air.org> writes:
No overt mistakes, but multiple infelicities. Don't listen to guys who
want to create sequences of variable names, it is (almost) invariably
the wrong idea.
Lessee, that was basically

byschool <- split(mansfield.dat, mansfield.dat$schirn) 

below, you use only 4 variables from the data frame and under
different names, so maybe first extract and rename them and have

#--------------
# code should be executable from here on

vars <- c("bpra3ccf", "bprr3ccf", "bprl3ccf", "bpri3ccf")
d2 <- mansfield.dat[vars]
names(d2) <- c("AV", "RP", "LT", "IT")
byschool <- split(d2, mansfield.dat$schirn)

# now to get the averages, you can do

mnList <- lapply(byschool, colMeans)

# now, let's do a little function to do one of your plots. It will have
# three arguments, the mean vector, the number of the school, and the
# name of the school

doPlot <- function(mn, no, name)
{
   # (I won't argue with your filename scheme)
   pdf(file=paste("school", no, "rel.pdf", sep="")
   # The barplot should get the names right automagically now:
   barplot(mn, width=c(.5,.5,.5,.5), ylim = c(0, 4), col=("salmon"))
   legend(1.0,3.8,legend=c("1=Relative Weakness", 
                "2=Similar to District", "3=Relative Strength"))
   title(main=(paste("Grade 3 Relative Strengths and Weaknesses", "\n",
      "School:", name, sep="")))
  
    dev.off()
}

# All set, now

num <- names(mnList)
mapply(doPlot, mnList, num, schname[num])

# done! End executable code
#--------------------------

Obviously, not having your data, all the above is untested, and most
likely not entirely bugfree.