Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

r programming
loops

How to use loops in R

Educative Answers Team

Loops allow for the repetition of tasks by grouping the parts that need to be repeated. Loops are especially helpful when variables need to be changed after each iteration.

There are three types of loops in R:

  • for loops
  • while loops
  • repeat loops

The following flow diagrams show how each loop progresses:

svg viewer

For loops

For loops run a fixed number of times. You initialize a variable with a specific value and write how many times you want the loop to run to the terminating condition. The text contained within the for loops will run that many times.

For ​example, lets print “Hello World” five times:

#for loop that starts with 1 and runs until the value is <= 5 
for (i in 1:5)
  print("Hello World")

The loop can also be used to automate any task that repeats itself. Let’s print the square of the numbers in an array:

#an array containing the first 5 digits
v <- c(1, 2, 3, 4, 5)

#for loop that starts at 1 and runs till the value is <=5
for (i in 1:5)
{
  #multiplies the number with itself and prints it
  j = v[i]*v[i]
  print(j)
}
  

Nested For loops

Nested for loops are for loops within for loops. The inner loop runs n number of times for every iteration of the outer for loop. Let’s print a matrix that contains 5 rows and 5 columns, and initialize them with the first four multiples of each digit.

# initialize a matrix of 5 x 5
mat <- matrix(0, 5, 5)

# for every value in the row, insert the multiples of i
for (i in 1:dim(mat)[1])
  for (j in 1:dim(mat)[2])
    mat [i, j] = i * j 

mat[1:5, 1:5]

While loop

The while loop is an infinite loop that keeps on running until a condition becomes true. This is ideal when you do not know the exact number of times a loop will need to run before it can be stopped.

It can also be used as a for loop to increment the value of a particular variable until the variable becomes equal to a given number.

Here is an example of the while loop running until the condition becomes true:

 v <- c(1, 4, 6 , 25 ,6)

#define index
index = 1
#run while loop until 25 is found
while(v[index] != 25){
  index = index + 1
}
#print the value that is found
print(v[index])
#print the index of the value found
print(paste("The value 25 is at index", index))

One key thing to note here is that the loop will keep on running if there is no value in the array that matches the condition. Therefore, it is very important to put a stop condition to avoid the system from crashing:

 v <- c(1, 4, 6 , 250 ,6)

#define index
index = 1
#run while loop until 25 is found
while(v[index] != 25){
  index = index + 1
  if(index > length(v)){
    print("Does not exist")
    break
  }
}
if(index < length(v)){
  #print the index of the value found
  print(paste("The value 25 is at index", index))
}

Repeat loop

The repeat loop is similar to the while loop, the only difference is that the loop is executed at least once. Here is an example:

response = "OK"

repeat{
  if(response == "OK"){
    print("Program Ended. The response is currently OK")
    break
  }
  else{
    print("Error! Type update response")
    break
  }
}

One important thing to note is that break can be used to end the loop before the initial condition ends. Once the loop is ended, the line immediately after the loop is executed.

RELATED TAGS

r programming
loops
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring