Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Output
if (logical expression) {
statements
} else {
alternative statements
}
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
if((num %% 2) == 0) {
print(paste(num,"is Even"))
} else {
print(paste(num,"is Odd"))
}
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
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
}
for(i in 1:10) {
print(“Hello”)
}
i=1
while(i<=10) {
print(i)
i=i+1
}
For Loop
repeat {
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
}
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