[R] multiple plots using a loop

Gabor Grothendieck ggrothendieck at gmail.com
Mon Feb 21 13:39:28 CET 2011


On Mon, Feb 21, 2011 at 4:25 AM, Darcy Webber <darcy.webber at gmail.com> wrote:
> Dear R users,
>
> I am trying to write myself a loop in order to produce a set of 20
> length frequency plots each pertaining to a factor level. I would like
> each of these plots to be available on the same figure, so I have used
> par(mfrow = c(4, 5)). However, when I run my loop below, it produces
> 20 plots for each factor level and only displays the last factor
> levels LF plots. I'm fairly new to loops in R, so any help would be
> greatly appreciated.
>
> I have provided an example data set below if required with just 4
> factors and adjusted par settings accordingly.
>
> Factor <- rep(factor(letters[1:4]), each = 10)
> Size <- runif(40) * 100
>
> par(mfrow = c(2, 2))
>
> for (i in Factor) {
> LFchart <- hist(Size[Factor == i], main = i,
> xlab = c("n =",length(Size[Factor == i])), ylab = "")
> }
>
> P.S. Also just a quick annoying question. My xlab displays:
> n =
> 120
> I would like it to display:
> n = 120
> but just cant get it to work. Any thoughts.
>

In the above example Factor has length 40 so the for loop produces 40
plots and you see the last 4.  You really want to loop over the levels
of Factor, not Factor itself:

for(i in levels(Factor)) {
...
}


-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list