for(value in range_of_values){
statement print(statement)
}
Creating a Basic For Loop
for
loop when you’re dealing with numeric values.
One of the key tenets of programming is the DRY principle: Don’t Repeat Yourself. Essentially, this boils down to not repeating your code ad nauseum to change only one or two things. This is particularly useful for computationally intensive workflows that would require changing tens or hundreds of items. That’s where the for
loop comes into play.
First, let’s look at the basic syntax of a for
loop. When you write one, you’re telling the computer “run this piece of code (statement
) some number of times (range_of_values
) in this spot (value
).”
And that’s it! Congratulations, now you know the syntax for a basic for
loop! Now let’s see it in practice. Now let’s put it into practice.
For more help on for
loops and other iterative processes, make sure to check out the R for Data Science book by Hadley Wickham and Garrett Grolemund!