Skip to content
Prev 247633 / 398503 Next

tips for looping over a category for beginner

On 2011-01-17 22:48, Ben Harrison wrote:
Since you don't provide data, let's borrow from the
help(droplevels) page:

aq <- transform(airquality,
         Month = factor(Month, labels = month.abb[5:9]))

str(aq)
#'data.frame':   153 obs. of  6 variables: |
# $ Ozone  : int  41 36 12 18 NA 28 23 19  |
# $ Solar.R: int  190 118 149 313 NA NA 29 |
# $ Wind   : num  7.4 8 12.6 11.5 14.3 14. | etc
# $ Temp   : int  67 72 74 62 56 66 65 59  |
# $ Month  : Factor w/ 5 levels "May","Jun |
# $ Day    : int  1 2 3 4 5 6 7 8 9 10 ... |

Now see if the following give you some R inspiration:

  plot(Ozone ~ Temp, data = aq)

  plot(Ozone ~ Temp, data = aq, subset = {Month == "Sep"})

  boxplot(Ozone ~ Month, data = aq)

  boxplot(Ozone ~ Month, data = aq,
                         subset = {Month != "Aug"})

  boxplot(Ozone ~ Month, data = aq,
      subset = {!(Month %in% c("Jul", "Aug"))})

  boxplot(Ozone ~ Month,
      data = droplevels(subset(aq, subset = {Month != "Aug"})))

  boxplot(Ozone ~ Month,
      data = droplevels(subset(aq, !(Month %in% c("Jul", "Aug")))))

BTW, attach() is not usually a good idea; have a look at ?with.

Peter Ehlers