How to write the first for loop in R
After setting this up, there is a display method that delivers something like what you requested:. Once the for loop has executed the code chunk for every year in the vector, the loop stops and goes to the first instruction after the loop block. They allow you to automate parts of your code that are in need of repetition.
Suppose you want to do several printouts of the following form: The year is [year] where [year] is equal to , , up to You can do this as follows:. You immediately see this is rather tedious: This violates the DRY principle, known in every programming language: In this case, by making use of a for loop in R, you can automate the repetitive part:. The best way to understand what is going on in the for loop, is by reading it as follows: Once the for loop has executed the code chunk for every year in the vector, the loop stops and goes to the first instruction after the loop block.
See how we did that? By using a for loop you only need to write down your code chunk once instead of six times. The for loop then runs the statement once for each provided value the different years we provided and sets the variable year in this case to that value.
You can even simplify the code even more: As a last note on the for loop in R: For example you could have used i , a commonly-used variable in for loops that stands for index:.
This produces the exact same output. Suppose you need to print all uneven numbers between 1 and 10 but even numbers should not be printed. In that case your loop would look like this:. Notice the introduction of the next statement. When i is between 1 and 10 we enter the loop and if not the loop stops. In case we enter the loop, we need to check if the value of i is uneven. In case the remainder is non zero, the if statement evaluates to TRUE and we enter the conditional. Here we now see the next statement which causes to loop back to the i in 1: In this short tutorial you got acquainted with the for loop in R.
While the usage of loops in general should be avoided in R, it still remains valuable to have this knowledge in your skillset. It helps you understand underlying principles, and when prototyping a loop solution is easy to code and read.
In case you want to learn more on loops, you can always check this R tutorial. I am mainly looking for some work around. R provides an array-class that might offer some of the features illustrated but doesn't have a print method that would immediately display as you demonstrated.
Adios to Winter Bash