for(value in range_of_values){
statement print(statement)
}
Creating a Basic For Loop
Learn how to write a 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.
Let’s say Europe is experiencing a heat wave, but I’m not quite grasping the context of how bad it is because I’m not familiar with the Celsius temperature scale. I know the average temperatures are somewhere between 35-40°C, so I’ll write a quick function to convert the temperatures into Fahrenheit! But that spans over five numbers, and writing that function out five individual times goes against the DRY principle. This gives us the perfect excuse to write a for
loop.
The equation for converting temperatures from Celsius to Fahrenheit is the following. \[(deg C*1.8) + 32\] Knowing that conversion formula, here’s how I’d write my for
loop:
for(degC in 35:40){
# Write your statement. Make sure the output of the statement is assigned to an object,
# otherwise R will only remember the very last conversion value.
<- (degC*1.8) + 32
fahr
# Print the outputs
print(fahr)
}
[1] 95
[1] 96.8
[1] 98.6
[1] 100.4
[1] 102.2
[1] 104
Yep, that’s pretty toasty!
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!