ยง2024-12-04

In R, there are three types of loops:

  1. while loop
# variable to store current number
number = 1
# variable to store current sum
sum = 0
# while loop to calculate sum
while(number <= 10) {
  # calculate sum
  sum = sum + number
  # increment number by 1
  number = number + 1
}
print(sum)
# [1] 55
  1. while Loop With break Statement

The break statement in R can be used to stop the execution of a while loop even when the test expression is TRUE. For example,

number = 1
# while loop to print numbers from 1 to 5
while(number <= 10) {
  print(number)
  # increment number by 1
  number = number + 1 
  # break if number is 6
  if (number == 6) {
    break
  }
}
[1] 1
[1] 2
[1] 3
[1] 4

3: while Loop With next Statement

number = 1
# while loop to print odd number between 1 to 10
while(number <= 10) {
  # skip iteration if number is even
  if (number %% 2 == 0) {  
    number = number + 1
    next
  }
  # print number if odd
  print(number)
  # increment number by 1
  number = number + 1  
}
[1] 1
[1] 3
[1] 5
[1] 7
[1] 9
  1. for loop

A for loop is used to iterate over a list, vector or any other object of elements.

numbers = c(1, 2, 3, 4, 5)
# for loop to print all elements in numbers
for (x in numbers) {
  print(x)
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5