R, lesson 4
Programs become useful when they react to their input: charge a child less than an adult, warn
when a battery is low, say "freezing" below zero. In R the tool for this is if.
The condition goes in parentheses, and the code to run goes in braces. If the condition is
FALSE, R skips the block.
Add else for the other case, and chain else if to test several conditions in order. R runs
the first block whose condition is true and skips the rest:
One R detail trips people up: else must be on the same line as the closing brace } before
it. If } ends a line on its own, R thinks the if is finished and then fails on the lonely
else.
2 exercises to try what you just read.
| Operator | Meaning |
|---|---|
== | equal (two = signs; one = is assignment) |
!= | not equal |
<, <=, >, >= | less / greater than |
They work on text too: "apple" == "apple" is TRUE, and the comparison is case-sensitive.
&& is "and": true only if both sides are true.|| is "or": true if at least one side is true.! is "not": flips TRUE and FALSE.&& and || stop as soon as the answer is known, and they expect a single TRUE or FALSE on
each side. R also has single & and |, which compare whole vectors element by element; you
will use those for filtering data later. Inside if, use the doubled forms.
The condition of an if must be exactly one TRUE or FALSE. If it is NA (for example
because a number failed to convert), R stops with an error, which is better than silently taking
the wrong branch.
In R, if is an expression, so you can store its result:
For a quick check on whole numbers, the remainder operator helps: n %% 2 == 0 is TRUE for
even numbers.
Read a person's age (a whole number) and print the ticket type and price:
Child: 5Adult: 9Senior: 6Sample input:
Sample output:
Read a year and print leap if it is a leap year, or common if it is not. A year is a leap
year if it is divisible by 4, except years divisible by 100, which are leap years only if
they are also divisible by 400.
Sample input:
Sample output:
temp <- -3
if (temp < 0) {
cat("Freezing!\n")
}if (temp < 0) {
cat("Freezing\n")
} else if (temp < 15) {
cat("Cool\n")
} else {
cat("Warm\n")
}age <- 70
student <- FALSE
if (age >= 65 || student) {
cat("Discount applies\n")
}label <- if (temp < 0) "ice" else "water"30Adult: 92024leap