The language has available a conditional construction of the form
if (expr
) expr
else expr
where expr
must evaluate to a logical value and the
result of the entire expression is then evident.
There is also a for-loop construction which has the form
for (name in expr
) expr
where name is the loop variable. expr
is a vector
expression, (often a sequence like 1:20), and expr
is often
a grouped expression with its sub-expressions written in terms of the dummy
name. expr
is repeatedly evaluated as name ranges
through the values in the vector result of expr
.
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.)
Other looping facilities include the
repeat expr
statement and the
while (condition) expr
statement. The break statement can be used to terminate any loop abnormally, and next can be used to discontinue one particular cycle.
Control statements are most often used in connection with functions
which are discussed in §
, and where more examples will
emerge.