[R] Looping syntax?

Thomas Lumley tlumley at u.washington.edu
Fri Jun 29 20:05:49 CEST 2001


On Fri, 29 Jun 2001, Michaell Taylor wrote:

>
>
> Sorry for what I hope is an unchallenging question for R veterans.
>
> I have a question regarding looping syntax, though I know this should be
> avoided if possible in R - as in most other stat languages with which I am
> familiar.
>
> I would like to perform a series of operations on the subsets as defined by
> condition. Given the following data frame
>
> condition	X 	Y
> aa		4	5
> aa		8	9
> .
> .
> bb		8	4
> bb		3 	9
> .
> .
> more ..
>
> There are over 100 condition states, each with several hundred observations.
> For ease of this example, lets assume that I wish to make XY plots of each of
> the 100 condition states, with In other words, I need a structure like the
> following

I think you want something like

for(state in unique(condition)){
	postscript(paste("figure",state,sep=""),height=3,horiz=FALSE)
	these<-condition %in% state
	plot(X[these],Y[these],xlab="X",ylab="Y",
		main=paste("Condition is",state))
	dev.off()
}


The loop could be replaced with sapply(), but I would expect that the file
access would be the rate-limiting step so sapply() wouldn't help a lot.
The whole thing could also be done with tapply() or by(). This is left as
an exercise for the reader.


	-thomas

Thomas Lumley			Asst. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list