OneBite.Dev - Coding blog in a bite size

do a for loop in R

Code snippet on how to do a for loop in R

  for(i in 1:10){
    print(i^2)
  }

This code is a simple example of a for loop in R. The loop starts with the line “for (i in 1:10)” which means that the code within the braces (“{ }”) will be executed 10 times, from 1 to 10. On that line, “i” is a variable that will take each of the values in the sequence (1, 2, 3, 4, 5, 6, 7, 8, 9, 10). For every single iteration of the loop, the current value of i will be printed out (“print(i^2)”). At the end of that line, the value of i will be increased by one and the loop will start again. The loop will stop when the variable i reaches 10, so it will happen 10 times in total.

r