Conditional execution
The first control construct examined is the if
statement. An if
statement will determine whether or not a code block should be executed, and it has an optional else
statement. An additional if
statement can be chained to an else
statement to create a cascade of options.
In its most basic form, an if
statement has the following form:
if(condition) code block
The condition can be a logical statement constructed from the operators given in the next table, or it can be a numeric result. If the condition is numeric, then zero is considered to be FALSE
, otherwise the statement is TRUE
. The code block can either be a single statement or a set of statements enclosed in braces:
> # check if 1 is less than 2 > if(1<2) + cat("one is smaller than two.\n") one is smaller than two. > if(2>1) { + cat("But two is bigger yet.\n") + } But two is bigger yet.
Note that a comment is included in the previous code. The #
character is used to denote...