Lecture 5: Control Statements
R control statements: IF & FOR
Ivan Belik
Assembled and built based on:
https://openlibra.com/en/book/download/an-introduction-to-r-2
https://cran.r-project.org/doc/manuals/R-intro.pdf
http://www.programiz.com/r-programming/if-else-statement
http://www.programiz.com/r-programming/examples/odd-even
R: Basics
• Control flows are required when you want a program to make a decision
• For example, you may want your program to make a decision and execute depending on different situations
• There are three fundamental control flows in R:
• if
• for
• while
R: Basics
We will start with if-statement, but first we should learn two things:
1. Interactive Input
2. Boolean Logic
R: Basics
1. Interactive Input
R: Basics: Interactive input
• if you need to enter data in R interactively:
A <- readline(prompt = "Enter your name: ")
class(A)
B <- readline(prompt = "Enter your age: ")
class(B)
• procedure:
1. R requests to enter your name (from the keyboard)
2. R requests to enter you age (from the keyboard)
• readline()-function reads a line from the terminal (in the interactive mode/console)
• prompt = “ ” -string is printed when you ask user to input data
R: Interactive Input
• Data entered via readline is a string type:
• Code gives us an error
• We should convert the entered value to the number mode (remember previous lecture):
• as.numeric() for floating point numbers
• as.integer() for integer numbers
R: Interactive Input
• We convert our input using as.numeric() function:
R: Basics
2. Boolean Logic
R Logical operators
• Logical operators are crucial for all sorts of data manipulation
• When R evaluates statements containing logical operators it will return either TRUE or FALSE
• We will learn how to use logical operators based on BOOLEAN LOGIC
R: Logical operators
• There are three fundamental logical operators:
• AND: “&”
• OR: “|”
• NOT: “!”
• The meaning of these operators is similar to their meaning in English
Logical Conjunction (and) Logical Disjunction (or)
a b a and b a b a or b
T T T T T T
T F F T F T
F T F F T T
F F F F F F
• Note: T is True; F is False
R: Logical operators
• Logical Conjunction: AND
… in R: & Logical Conjunction (and)
Interpretation: a b a and b
1. "Blue is a color and 7 + 3 = 10."
T T T
(T and T = T) Since both facts are true, the entire sentence is true.
2. "One minute = exactly 60 seconds and One hour = exactly 55 minutes "
T F F
(T and F = F) Since the second fact is false, the entire sentence is false.
3. "One hour = exactly 55 minutes and one minute = exactly 60 seconds."
F T F
(F and T = F) Since the first fact is false, the entire sentence is false.
4. "3 + 4 = 6 and Bergen is a capital of Norway."
F F F
(F and F = F) Since both facts are false, the entire sentence is false.
R: Logical operators
• Logical Disjunction: OR
… in R: | Logical Disjunction (or)
Interpretation: a b a or b
1. "Blue is a color or 7 + 3 = 10."
(T or T = T) Since both facts are true, the entire sentence is true. T T T
2. "One minute = exactly 60 seconds or One hour = exactly 55 minutes "
(T or F = T) Since the first fact is true, the entire sentence is true. T F T
3. " One hour = exactly 55 minutes or One minute = exactly 60 seconds "
(F or T = T) Since the second fact is true, the entire sentence is true. F T T
4. "3 + 4 = 6 or Bergen is a capital of Norway."
(F or F = F) Since both facts are false, the entire sentence is false. F F F
R: Logical operators
Logical Conjunction (and)
a b a and b
T T T
T F F
F T F
F F F
Logical Disjunction (or)
a b a or b
T T T
T F T
F T T
F F F
Conditional execution:
if – statement
R: IF – statement
Frequently, we need to check conditions
Decision making. In words:
Statements:
A = “The weather is good”
B = “We go hiking”
C = “We are watching TV”
Conditional execution:
IF A is TRUE
THEN B
ELSE C
IF A is not TRUE # (not TRUE) gives FALSE
THEN C
ELSE B
R: IF – statement
• Let’s write a very simple conditional using the if() control-flow construct.
• The if() construct is simply a control statement
• It takes a conditional statement as its argument
• Then, depending on the evaluation, it initiates some other statement(s)
• Formal IF – notation in R:
IF-THEN (True-block only): IF-THEN-ELSE:
if (condition(s)) { if (condition(s)) {
statement statement 1
} } else {
statement 2
}
R: IF – statement
• Let’s check if 1 + 1 = 2 and if so to print something to the screen with the print() function:
IF-THEN (True-block only):
if (condition(s)) {
statement
}
• You can see that the if() statement evaluated to TRUE in this case
• It activated the print() function.
R: IF – statement
• If the if() statement is FALSE then nothing happens:
IF-THEN (True-block only):
if (condition(s)) {
statement
}
R: IF – statement
• When we want R to do something if the conditional is FALSE,
we would have to add the ELSE statement:
IF-THEN-ELSE:
if (condition(s)) {
statement 1
} else {
statement 2
}
• Note: if and else are case sensitive key words
R: IF – THEN – ELSE
Number is ODD or EVEN:
Outputs:
Enter a number: 89
[1] "89 is Odd"
Enter a number: 20
[1] “20 is Even"
R: The ifelse() function
• Instead of using the if() and else control statements, you can just use the ifelse() - function.
• The function takes the following arguments: test, yes and no.
• This function comes in very handy to do data manipulations
• To specify key words (test, yes and no) is not necessary
R: Nested IF Control Flow Statements
• Before we learn nested Control Flows:
• it is useful to introduce some R’s random number generating functions:
• Detailed descriptions of the given functions are available in R documentation
• Before we move to Nested IF example: a few words about some useful functions
• runif() function – see the brief description (in the table) above
• cat() function:
• almost the same as print() function
• it simply converts arguments to characters, concatenates them, and displays the result to console.
R: print and cat
• cat() versus print():
• cat() converts arguments to characters and concatenates them
• print() does not concatenate the arguments
cat print
R: print and cat
• cat() versus print():
• print() returns value
• cat() does not return anything
PRINT CAT
R: cat()
• cat() is also very useful when we need to display results in several lines
• That can be done simply by using:
• “\n” to start a new line
• sep= a character vector of strings to append after each element.
• Note: sep= "" means “no-space” separator
a = 10
b = 20
cat("a is equal to", a, "\n", sep="", "b is equal to", b)
Result:
a = 10 b = 20 cat("a is equal to", a, "\n", sep=" | ", "b is equal to", b)
Result:
R: Nested IF Control Flow Statements
r <- runif (n = 1, min = 0, max = 1) # generate a random number between 0 and 1
r
if (r < 0.2) {
cat ( "r is " , r , " which is smaller than 0.2 ")
} else {
if (0.2 < r & r < 0.5 ) {
cat ( "r is " , r , " which is between 0.2 and 0.5 " )
} else {
if(r > 0.5 & r < 0.9) {
cat ( "r is " , r , " which is greater than 0.5 " )
} else {
cat ( "r is " , r , " which is greater than 0.9 " )
}
}
}
• RESULT:
r is 0.2432193 which is between 0.2 and 0.5
Loops:
for – statement
R: for - statement
• for repeatedly executes a block of statements the specified number of times.
• Repetition of statements (D and C in figure) using for is called iteration
• The for statement is also called for-loop
• Formal FOR – notation in R:
for (value in sequence) {
statement
}
R: for - statement
• Example: for (value in sequence) {
statement
# To sum all elements in the vector: }
my_vector <- c(1, 2, 3, 4, 5, 6, 7)
count <- 0
for (i in my_vector) {
count <- count + i
}
print(count)
# same result if we apply sum() function:
sum(my_vector)
• RESULT:
[1] 28
R: for - statement
• Consider more advanced example based on the “iris” data frame
R: for - statement
• Let’s make our example a bit more interesting
• We will create a new empty data frame called My_frame
• My_frame will have one variable Sepal.Width (the same name as in iris data frame)
• Next, we populate My_frame by Sepal.Width values (from iris) that are greater than 3.7
• We will employ for-statement to solve this problem
R: for - statement
R: for - statement
• R has detected 15 iris$Sepal.Width-values greater than 3.7
FOR - statement:
more advanced examples
(optional)
R: FOR statement. Example 1
Multiplication Table of a Number. The user should be able to enter the number.
# Multiplication Table (from 1 to 10)
# user input:
num = as.integer(readline(prompt = "Enter a number: "))
# use for loop to iterate 10 times
for(i in 1:10) {
print(paste(num,'x', i, '=', num*i))
} Result:
R: FOR statement. Example 2
Factorial of a Number. The user should be able to enter the number.
• The factorial of a positive integer n, denoted by n!
• It is the product of all positive integers less than or equal to n
• For example: 4! = 1 x 2 x 3 x 4 = 24
• Note: The value of 0! is 1
R: FOR statement. Example 2
Factorial of a Number. The user should be able to enter the number.
# user input
num = as.integer(readline(prompt="Enter a number: "))
factorial = 1
# check is the number is negative, positive or zero
if(num < 0) {
print("Sorry, no factorials for negative numbers")
} else if(num == 0) {
print("0! is 1")
} else {
for(i in 1:num) {
factorial = factorial * i
}
print(paste("The factorial of", num ,"is",factorial))
} Result:
R: FOR statement. Example 3
Check whether the Number is Prime. The user should be able to enter the number.
• A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers.
• For example, 5 is prime because the only ways of writing it as a product,
1 × 5 or 5 × 1, involve 5 itself.
• However, 6 is composite:
it is the product of two numbers (2 × 3) that are both smaller than 6.
The first 25 prime numbers (all the prime numbers less than 100) are:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
R: FOR statement. Example 3
Check whether the Number is Prime. The user should be able to enter the number.
# user input
num = as.integer(readline(prompt="Enter a number: "))
flag = 0
# proceed if "num" is greater than 1
if(num > 1) {
# check for factors
flag = 1 # flag is "1" if the number is prime
# Check if 'num' is divisible by any number from 2 to 'num – 1' (by any smaller number)
for(i in 2:(num-1)) {
if ((num %% i) == 0) { # if factor exists in the range, the number is not prime
flag = 0 # flag: the number is not prime
break
}
}
}
if(num == 2) { flag = 1 }
Result:
if(flag == 1) {
print(paste(num,"is a prime number"))
} else {
print(paste(num,"is not a prime number"))
}