Doing mathematics with R: Control structures
Conditional instruction
In the interactive R session below, there is a warning first because the sqrt
function only calculates within the non-negative real numbers.
> sqrt(-3)
[1] NaN
Warning message:
In sqrt(-3) : NaNs produced
If you want to be able to calculate square roots without any worries, you must be able to distinguish between negative and non-negative numbers. You can use a conditional statement via if
for this:
Onderstaand R script
x <- -3
if (x<0) {
cat("There is no real root of", x)
} else {
cat("sqrt(",x,") =", sqrt(x))
}
levert bij uitvoeren van de instructies de volgende tekst op
There is no real root of -3
The general form of a conditional statement ( if statement) is below. Read the explanation:
Conditional instruction
if (condition) {
indented instructions in case the condition is met
} else {
indented instructions in case the condition is not met
}
In our first example, we gave a variable a value that depended on a condition. This is so common that an inline ifelse
conditional statement is also possible in R. We could also have used the following R statement in the first example:
> root <- ifelse(x<0, "no number", sqrt(x))
We give another example session in R of the two kinds of conditional instructions, where the calculation depends on whether an integer is even or odd. The conditional instruction is spread over several lines, and the plus signs indicate that the instruction is not yet complete.
> x <- 5
> if (x %% 2 == 0) {
+ x <- x %/% 2
+ } else {
+ x <- 3*x + 1 + }
> x
[1] 16
> x <- ifelse(x %% 2 == 0, x %/% 2, 3*x + 1)
> x [1] 8
Finally, we give some examples of chained and nested conditional instructions. Take a good look at them, try to understand them and read the explanations of the examples.
If you run the following R script
numbers_NL <- c("een", "twee", "drie")
choice <- sample(numbers_NL, 1)
cat(choice, "\n")
if (choice == "een") {
cat("one\n")
} else if (choice == "twee") {
cat("two\n")
} else if (choice == "drie") {
cat("three\n")
} else {
cat("???\n")
}
switch(choice,
"een" = cat("one\n"),
"twee" = cat("two\n"),
"drie" = cat("three\n")
)
this may yield the following output (depending on the actual choice made):
drie
three
three
For the example below, read the explanation for information about formatting printed numbers.
If you run the following R script
r <- runif(1) # a random number between 0 and 1
io <- sprintf("r = %.2f\n", r) # formatted text
cat(io)
if (0.25<r) {
if (r<0.75) {
io <- sprintf("%.2f is a number between 0.25 and 0.75\n", r)
}
}
cat(io)
this can produce the following output:
r = 0.39
0.39 is a number between 0.25 and 0.75
0.39 is a number between 0.25 and 0.75