<- function(x) {
test_sign if (x > 0) {
"x is positif"
else if (x < 0) {
} "x is negatif"
else {
} "x is equal to zero"
} }
Control flow
Control flow statements alter the linear execution of code, allowing for one or another section of code to be executed, or for one section of code to be executed multiple times.
Conditionals
Conditionals determine which section of code is to be ran based on predicates. A predicate is a test that returns either TRUE
or FALSE
.
Here is an example:
test_sign()
is a function that accepts one argument. Depending on the value of that argument, one of three snippets of code is executed:
test_sign(3)
[1] "x is positif"
test_sign(-2)
[1] "x is negatif"
test_sign(0)
[1] "x is equal to zero"
Loops
Loops allow to run the same instruction on various elements:
for (i in 1:10) {
print(i)
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10