0
0
R-programmingHow-ToBeginner ยท 3 min read

How to Use For Loop in R: Syntax and Examples

In R, a for loop repeats a block of code for each value in a sequence. Use the syntax for (variable in sequence) { code } to run code multiple times with different values.
๐Ÿ“

Syntax

The for loop in R runs code repeatedly for each item in a sequence.

  • variable: a name that holds the current item in the loop.
  • sequence: a vector or list of values to loop over.
  • code: the commands inside curly braces { } that run each time.
r
for (variable in sequence) {
  # code to run
}
๐Ÿ’ป

Example

This example prints numbers 1 to 5 using a for loop.

r
for (i in 1:5) {
  print(i)
}
Output
[1] 1 [1] 2 [1] 3 [1] 4 [1] 5
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Forgetting the in keyword.
  • Not using curly braces { } when running multiple lines inside the loop.
  • Using a sequence that is empty or NULL, so the loop never runs.
r
## Wrong: missing 'in'
# for (i 1:3) {
#   print(i)
# }

## Correct:
for (i in 1:3) {
  print(i)
}
Output
[1] 1 [1] 2 [1] 3
๐Ÿ“Š

Quick Reference

Tips for using for loops in R:

  • Use 1:n or a vector for the sequence.
  • Always use curly braces { } for multiple commands.
  • Use descriptive variable names for clarity.
  • Remember loops can be slow for large data; consider vectorized functions.
โœ…

Key Takeaways

Use for (variable in sequence) { } to repeat code for each item in R.
Always include curly braces { } when running multiple commands inside the loop.
The loop variable takes each value from the sequence one by one.
Common errors include missing the in keyword or forgetting braces.
For large data, consider alternatives to loops for better performance.