0
0
R Programmingprogramming~5 mins

For loop in R Programming

Choose your learning style9 modes available
Introduction
A for loop helps you repeat a set of actions many times without writing the same code again and again.
When you want to print numbers from 1 to 10.
When you need to add up all values in a list.
When you want to apply the same change to each item in a group.
When you want to check each element in a collection one by one.
Syntax
R Programming
for (variable in sequence) {
  # code to repeat
}
The variable takes each value from the sequence one by one.
The code inside the curly braces { } runs for each value.
Examples
Prints numbers 1 to 5, one by one.
R Programming
for (i in 1:5) {
  print(i)
}
Prints each letter in the list.
R Programming
for (letter in c('a', 'b', 'c')) {
  print(letter)
}
Prints even numbers from 2 to 10.
R Programming
for (num in seq(2, 10, by=2)) {
  print(num)
}
Sample Program
This program goes through numbers 1 to 4, calculates their squares, and prints the result.
R Programming
numbers <- 1:4
for (n in numbers) {
  square <- n^2
  print(paste(n, "squared is", square))
}
OutputSuccess
Important Notes
Make sure the sequence you use in the for loop is not empty, or the loop will not run.
Indent the code inside the loop to keep it clear and easy to read.
Summary
A for loop repeats actions for each item in a sequence.
Use it to avoid writing repetitive code.
The loop variable changes automatically with each repetition.