Conditional statements and loops

Statistical Laboratory

Alessandro Ortis - University of Catania

Conditional statements (if, if/else, switch)

In [1]:
x <- 60
y <- 50

if(x>y)
{
   print("x is greater than y")
}
[1] "x is greater than y"
In [2]:
x <- 30
y <- 50

# the 'else' clause is selected...
# ...when x<=y
# ...when x>y is FALSE
if(x>y) {
   print("x is greater than y")
} else {
   print("x is NOT greater than y")

}
[1] "x is NOT greater than y"
In [6]:
val <- 2*2

x <- switch(val,
   "first",
   "second",
   "third",
   10+9,
   "fifth"
)
print(x)
[1] 19
In [4]:
?switch
In [11]:
x <- c(2,3,6,2,12,6,8,3,2)

operation = "median"

result <- switch(operation,
         mean = mean(x),
         median = median(x),
         variance = var(x),
         "not allowed")  # default value
    
print(result)
[1] 3

Loops (repeat, while, for)

In [24]:
v <- c("Hello","folks!")
cnt <- 2

repeat {
   print(v)
   cnt <- cnt+1
   
   if(cnt > 5) {
      break
   }
}
# after the break it goes here!
print(cnt)
[1] "Hello"  "folks!"
[1] "Hello"  "folks!"
[1] "Hello"  "folks!"
[1] "Hello"  "folks!"
[1] 6
In [12]:
v <- c("Hello","while")
cnt <- 2

while (cnt < 7) {
   print(v)
   cnt = cnt + 1
}
print(cnt)
[1] "Hello" "while"
[1] "Hello" "while"
[1] "Hello" "while"
[1] "Hello" "while"
[1] "Hello" "while"
[1] 7
In [32]:
# we can interrupt the while earlier by using 'break'
cnt <- 2
while (cnt < 7) {
   print(v)
   cnt = cnt + 1
   if(cnt == 4)
       break
}
print(cnt)
[1] "Hello" "while"
[1] "Hello" "while"
[1] 4
In [33]:
v <- 1:10
for (i in v) {   
   print(i)
   print(2*i)
}
[1] 1
[1] 2
[1] 2
[1] 4
[1] 3
[1] 6
[1] 4
[1] 8
[1] 5
[1] 10
[1] 6
[1] 12
[1] 7
[1] 14
[1] 8
[1] 16
[1] 9
[1] 18
[1] 10
[1] 20
In [39]:
list_of_elements <- 1:10
for (element in list_of_elements) 
{   
   print(element*2)
}
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10
[1] 12
[1] 14
[1] 16
[1] 18
[1] 20
In [40]:
list_of_elements <- 1:10
for (element in list_of_elements) 
{   
   print(element*2)
   if (element == 5)
       break
}
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10
In [13]:
list_of_elements <- 1:10
for (element in list_of_elements) 
{   
   # this part is always executed
   print(element)
   if(element > 5)
       next
   # this part will be skipped by using 'next' (i.e., continue)
   print(element*2)
}
[1] 1
[1] 2
[1] 2
[1] 4
[1] 3
[1] 6
[1] 4
[1] 8
[1] 5
[1] 10
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

Exercise

Given the following vector of numbers, define a code to insert the even elements in the 'even' vector, the odd elements in the 'odd' vector and skip all the zeros. hint: the operator '%%' returns the reminder of a division.

In [14]:
odd = c()
even = c()
el_vector = c(1,2,3,4,0,10,2,0,4,6,7,8,9,0,1)
In [ ]: