Skip to content

tips for looping over a category for beginner

10 messages · Ivan Calandra, Dennis Murphy, Ben Harrison +2 more

#
Hi,

First a good tip when you ask on the R list is to provide data in a way 
that we can readily use it. I think the best way to do it is to copy the 
output of dput(tc) into the email you write.

There might be better ways to do what you want, but here is what I would do:

#first subset what you need:
tc_clay <- tc[LithClass=="clay",]
#or
tc_not_clay <- tc[LithClass!="clay",]

#you might need to drop the unused levels if you don't want all of them 
to be plotted without values. Two ways (at least) to do it:
tc_clay <- factor(tc_clay)
tc_not_clay <- droplevels(tc_not_clay)

#then you can plot
plot(tc_clay$Conductivity~tc_clay$Depth)
boxplot(tc_not_clay$Conductivity~tc_not_clay$LithClass)

I hope it will help you get started.
Ivan

Le 1/18/2011 07:48, Ben Harrison a ?crit :

  
    
#
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
#
On Jan 18, 2011, at 7:32 PM, Ben Harrison wrote:

            
PLEASE. (re?-)read the Posting Guide.
David Winsemius, MD
West Hartford, CT
#
Hi,

If you don't find droplevels(), then you should install the latest 
version of R (2.12.1). It's always a good thing, even more if you're 
starting.

Ivan

Le 1/19/2011 01:27, Ben Harrison a ?crit :

  
    
#
On 2011-01-18 16:27, Ben Harrison wrote:
[...snip...]
plot has many methods; see with methods(plot).
If you go to the help page for plot you'll be pointed
to plot.default and plot.formula (under 'See Also').
Have a look at those to see what the difference is.
The formula method is useful in that it permits you
to set the 'data' argument (which obviates the need
for 'attach'ing.

[...snip...]
I wouldn't call it a sin, but I find alternatives like with()
and 'data=' much more convenient.

Peter Ehlers