[R] Plot factors with a loop

Sam Player samtplayer at gmail.com
Sun Sep 20 13:22:46 CEST 2009


# I have a dataframe with a factor and data:

a <- rep(c("a", "b"), c(6,6))
df <- data.frame(f=a, d=rnorm(12))
df

# I want to make a single plot with boxplots of each factor. I need to 
do it via a loop as I would like to apply it to other dataframes with 
many factors. The following is a loop that produces a boxplot of the 
last factor, which overwrites the previous factor.

for (i in levels(df$f)){
         z <- assign(as.character(i), as.vector(df[df$f==i,2], 
mode="numeric"))
         boxplot(z)
         }

# How can I stop the first factor being overwritten so that two boxplots 
are displayed in the plot. The result I need is also produced by:

boxplot(df[df$f=="a",2], df[df$f=="b",2])

# but I need it to be done through the loop. Thanks in advance!

# Sam

-- 
Sam Player, B.Sc.(Hons.) B.A.
Ph.D. Candidate, Faculty of Agriculture, Food & Natural Resources, University of Sydney

Email: splayer at usyd.edu.au

Agroecosystems Research Group
Room 214 J.R.A. McMillan Building A05
University of Sydney NSW 2006, Australia

Angkor Research Program
Room 305 Old Teachers College A22
University of Sydney NSW 2006, Australia




More information about the R-help mailing list