for (name in expr1 ) expr2
where name is the loop variable. expr1 is a vector expression, (often a sequence like 1:20), and expr2 is often a grouped expression with its sub-expressions written in terms of the dummy name. expr2 is repeatedly evaluated as name ranges through the values in the vector result of expr1 .
As an example, suppose ind is a vector of class indicators and we wish to produce separate plots of y versus x within classes. One possibility here is to use coplot() to be discussed later, which will produce an array of plots corresponding to each level of the factor. Another way to do this, now putting all plots on the one display, is as follows:
yc <- split(y, ind); xc <- split(x, ind)
for (i in 1:length(yc)){plot(xc[[i]], yc[[i]]);
abline(lsfit(xc[[i]], yc[[i]]))}
(Note the function split() which produces a list of vectors got by splitting a larger vector according to the classes specified by a category. This is a useful function, mostly used in connection with boxplots. See the help facility for further details.)
WARNING: The use of for() loops will result in relatively slow evaluation. While for() loops in . tend to be faster than in . they should be avoided if possible. Many functions, such as apply(), tapply(), sapply() and others, are written primarily to avoid using explicit for() loops.
Other looping facilities include the
repeat expr
statement and the
while (condition) expr
statement.
The break statement can be used to terminate any loop, possibly abnormally. This is the only way to terminate repeat loops.
The next can be used to discontinue one particular cycle and skip to the ``next''.
Control statements are most often used in connection with functions
which are discussed in §
, and where more examples will
emerge.