Sei sulla pagina 1di 35

Flow Control in R

Dr. Anuj Sharma


Information Systems Area
Outline
• if statement in R
• Branching- if…else statement
• if…else Ladder
• ifelse() Function
• For Loops
• While Loops
• Repeat
• Next and Break
• Nested Loops
Flow Control in R
if statement in R
• Decision making is an important part of
programming
• This can be achieved in R programming using the
conditional if...else statement
• if statement
if (test_expression) {
statement
}

• If the test_expression is TRUE, the statement gets


executed. But if it’s FALSE, nothing happens
Example
x <- 5
if(x > 0){
print("Positive number")
}

Output

[1] "Positive number"


Branching- if…else statement

if (logical expression) {
statements
} else {
alternative statements
}

else branch is optional and is only evaluated if logical


expression is FALSE

It is important to note that else must be in the same line as the


closing braces of the if statement.
Flowchart of if…else statement

x <- -5
if(x > 0){
print("Non-negative number")
} else {
print("Negative number")
}

Output
[1] "Negative number"
Example: Check Odd and Even Number
# Program to check if the input number is odd or even
# A number is even if division by 2 give a remainder of 0
# If remainder is 1, it is odd

num = as.integer(readline(prompt="Enter a number: "))

if((num %% 2) == 0) {
print(paste(num,"is Even"))
} else {
print(paste(num,"is Odd"))
}

Output 1 Copy the program in R Studio and Run


Enter a number: 89
[1] "89 is Odd"
if…else Ladder
• if…else ladder (if…else if…else) statement allows you
execute a block of code among more than 2 alternatives
• The syntax of if…else if…else statement is:
if ( test_expression1) {
statement1
} else if ( test_expression2) {
statement2
} else if ( test_expression3) {
statement3
… Only one statement
} else { will get executed
depending upon the
statement4 test_expressions
}
if…else Ladder
Example

x <- 0
if (x < 0) {
print("Negative number")
} else if (x > 0) {
print("Positive number")
} else
print("Zero")

Output

[1] "Zero"
Summary- Conditional Statements
• Perform different commands in different situations
• if (condition) command_if_true
• Can add else command_if_false to end
• Group multiple commands together with braces {}
• if (cond1) {cmd1; cmd2;} else if (cond2) {cmd3; cmd4;}
• Conditions use relational operators
• ==, !=, <, >, <=, >=
• Do not confuse = (assignment) with == (equality)
• = is a command, == is a question

• Combine conditions with and (&&) and or (||)


• Use & and | for vectors of length > 1 (element-wise)
ifelse() Function
• This is a shorthand function to the traditional if…else
statement
ifelse(test_expression, x, y)
• Here, test_expression must be a logical vector (or
an object that can be coerced to logical)
• The return value is a vector with the same length
as test_expression.
a = c(5,7,2,9)
ifelse(a %% 2 == 0,"even","odd")

Output
[1] "odd" "odd" "even" "odd"
If else.R
Loops in R
Loops in R
• Loops are used in
programming to repeat a
specific block of code
Syntax
for (val in sequence)
{
statement
}

Sequence is a vector and val takes on each of its


value during the loop.
In each iteration, statement is evaluated.
Loops
• When the same or similar tasks need to be performed
multiple times; for all elements of a list; for all columns of an
array; etc

for(i in 1:10) {
print(“Hello”)
}

i=1
while(i<=10) {
print(i)
i=i+1
}
For Loop

• For loops are used when


you need to execute a
block of code several
number of times
• It has 3 steps-
– Initialization
– checking the condition
– When condition becomes
false, exits the loop
Loops
• Most common type of loop is the for loop
• for (x in v) { loop_commands; }
• v is a vector, commands repeat for each value in v
• Variable x becomes each value in v, in order
• Example: adding the numbers 1-10
• total = 0; for (x in 1:10) total = total + x;

• Other type of loop is the while loop


• while (condition) { loop_commands; }
• Condition is identical to if statement
• Commands are repeated until condition is false
• while loops are useful when you don’t know number of iterations
while Loop
• “while loops” are used to loop until a
specific condition is met
while (test_expression)
{
Statement
}

• Here, test_expression is evaluated and


the body of the loop is entered if the
result is TRUE
• This is repeated each time
until test_expression evaluates to FALSE
Loops.R
repeat loop
• A repeat loop is used to iterate a
block of code multiple times
• There is no condition check in
repeat loop to exit the loop
• We must put a condition explicitly
inside the loop body and use
break statement to exit the loop

repeat {
statement
}

Read from loops.R


repeat loop
x <- 1
repeat { [1] 1
print(x) [1] 2
x = x+1 [1] 3
if (x == 6){ [1] 4
break [1] 5
}
}
How these two statements-
while and repeat differ?
Difference between the repeat and
while statement
• While loop basically defines when you are going to
enter the loop to execute the statements
• Repeat loop defines when you leave from the loop
after the execution of the statements.
• So these two statements are known as entry control
loop and exit control loop
break Statement
• A break statement is used inside a
loop (repeat, for, while) to stop the
iterations and flow the control
outside of the loop
• In a nested looping situation, where
there is a loop inside another loop,
this statement exits from the
innermost loop that is being
evaluated.
if (test_expression){
break
}

Read from loops.R


break Statement
# break statement

x <- 1:5
for (val in x) { [1] 1
if (val == 3){ [1] 2
break
}
print(val)
}
next Statement
• A next statement is useful when
we want to skip the current
iteration of a loop without
terminating it
• On encountering next, the R
parser skips further evaluation
and starts next iteration of the
loop
if (test_condition){
next
}

Read from loops.R


next Statement
# Next statement

x <- 1:5
for (val in x) { [1] 1
if (val == 3){ [1] 2
next [1] 4
} [1] 5
print(val)
}
Switch branching
• A switch statement is a selection control mechanism
that allows the value of an expression to change the
control flow of program execution via map and
search
• The switch statement is used in place of long if
statements which compare a variable with several
integral values
• It is a multi-way branch statement which provides
an easy way to dispatch execution for different parts
of code.
• This statement allows a variable to be tested for
equality against a list of values
Switch branching
Switch branching
vtr <- c(150,200,250,300,350,400)
option <-"min"
switch(option,
"mean" = print(mean(vtr)),
"min" = print(min(vtr)),
"max" = print(max(vtr)),
"median" = print(median(vtr))
)
Nested Loops
• It is similar to the standard for loop, which makes
it easy to convert for loop to a for each loop
• Unlike many parallel programming packages for
R, “for each loop” doesn’t require the body of for
loop to be turned into a function
• We can call this “a nesting operator” because it is
used to create nested for each loops

Potrebbero piacerti anche