Skip to content
Prev 194139 / 398500 Next

Plot factors with a loop

# 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