Performing the same operation multiple times, using multiple statements can be very exhausting. We can make our life easier by making use of loops.

x <- c(1,2,3,4,5,6,7)
# R is clever and understands what has to be done in this instance
x*x
## [1]  1  4  9 16 25 36 49
# This would be a much more traditional 'programming' style
for (i in seq(1:length(x))){
  print(x[i]*x[i])
}
## [1] 1
## [1] 4
## [1] 9
## [1] 16
## [1] 25
## [1] 36
## [1] 49

for

A for loop will perform a task’s’, enclosed within its {}, for N number of times, starting at i, incrementing i by a value of x, and will stop when it reaches the set max limit N.

x <- seq(1:10)

print("First for loop")
## [1] "First for loop"
# print numbers in x
for (i in x){
  print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
## [1] 10
x <- seq(2,20,2)

# print numbers in x
print("Second for loop")
## [1] "Second for loop"
for (i in x){
  print(i^sqrt(i))
}
## [1] 2.665144
## [1] 16
## [1] 80.55148
## [1] 358.3639
## [1] 1453.04
## [1] 5475.118
## [1] 19427.57
## [1] 65536
## [1] 211675.3
## [1] 658238.1

while

A while loop will perform a task’s’, until a condition is met. As soon as the condition is satisfied, it will stop performing the task.

x_sum <- 0
max_X <- 20
while(x_sum < max_X){
  x_sum <- x_sum+2
  print(x_sum)
}
## [1] 2
## [1] 4
## [1] 6
## [1] 8
## [1] 10
## [1] 12
## [1] 14
## [1] 16
## [1] 18
## [1] 20
# change max_X and re-run the while loop
 

Introduction to R by Dr. Sarath Chandra Dantu

This course material is available under a Creative Commons BY-SA license (CC BY-SA) version 4.0