Chapter 4Programming and functions
R is a full-fledged programming language, with standard programming constructs like conditional execution, loops, and subroutines (called functions in R). In this chapter we show how these constructs are implemented.
4.1 Conditional execution: if
and ifelse
Computer programs can choose different computations depending on whether a logical condition evaluates to true or false. The relational operators in R that perform such evaluation are listed in Section 2.5. The logical operators are & (and), |
(or), and ! (not).
The if
statement operates on logical vectors of length 1. A formal construction is
if(condition 1) { result 1 } else if (condition 2) { result 2 } else { result 3 }
For example
> x = -3 > if(x ...
Get Using R for Numerical Analysis in Science and Engineering now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.