R Lesson 16: R Loops

Advertisements

Hello everybody,

It’s Michael, and today’s lesson will be on loops in R. I’ve posted about loops before, but those were for my Java lessons. However, while there may be some differences between Java loops and R loops, the basic ideas are the same. In fact, two of the three main types of Java loops-while and for-are also the two main types of R loops. The do-while loop doesn’t exist in R…..at least not yet. In its place, R has something called the repeatloop.

Let’s demonstrate the forloop first:

Screen Shot 2019-06-02 at 1.02.22 PM

In this for loop, the factorials for the numbers 1-10 are printed. The i is a common symbol in R loops-it represents the indexes (or elements) of a loop. The i will traverse through all 10 elements of the loop-in this case, the numbers 1 through 10-and print out the factorials of each number along with the corresponding text-The factorial for , i , is, factorial(i).

  • In case you weren’t aware, the factorial of a number is the product of that number and all numbers below it (stopping at 1). So 4 factorial would be 24, since 4*3*2*1 equals 24. Factorials are denoted with an exclamation point by the number, so 4 factorial would be written as 4!. You might have come across this concept in your algebra class.

Now let’s take a look at the differences in syntax between a Java for loop and an R for loop (using the same factorial output)

R for loop:

for (i in 1:10)

{print(paste(“The factorial for” , i , “is” , factorial(i)))}

Java for loop:

int fac = 1;

for (int i = 1; i <= 10; i++)

{

fac *= i;

System.out.println(“The factorial of  ” + i + ” is ” + fac );

}

So, where are all of the differences? Let me name 5:

  1. The commands to print the output are different. Java requires System.out.println (or System.out.print). R requires print(paste()).
  2. Java needs 6 lines of code to do what R can accomplish in two lines-which is to calculate the factorials of the numbers 1-10 and print the specified output.
  3. The way to concatenate strings and numbers is different-Java requires a plus sign while R uses a comma
  4. You will often need to declare a variable outside the loop in Java (like I did with fac = 1). That is usually not necessary in R.
  5. The forloop parameters in R are much simpler than those in Java. Here’s how:
    • The Java for loop parameters go (initializing condition; condition to stop the loop; action to perform after each iteration)
    • The R for loop parameters go (index variable in starting value:ending value). The starting value:ending value part tells the loop the startpoint and endpoint.

Next, let’s demonstrate a nested for loop. Just like in Java, you can make nested for loops:

And here’s the output (it was too large to capture in a single screenshot):

[1] “I times J is 6”
[1] “I times J is 8”
[1] “I times J is 10”
[1] “I times J is 12”
[1] “I times J is 14”
[1] “I times J is 16”
[1] “I times J is 18”
[1] “I times J is 9”
[1] “I times J is 12”
[1] “I times J is 15”
[1] “I times J is 18”
[1] “I times J is 21”
[1] “I times J is 24”
[1] “I times J is 27”
[1] “I times J is 12”
[1] “I times J is 16”
[1] “I times J is 20”
[1] “I times J is 24”
[1] “I times J is 28”
[1] “I times J is 32”
[1] “I times J is 36”
[1] “I times J is 15”
[1] “I times J is 20”
[1] “I times J is 25”
[1] “I times J is 30”
[1] “I times J is 35”
[1] “I times J is 40”
[1] “I times J is 45”
[1] “I times J is 18”
[1] “I times J is 24”
[1] “I times J is 30”
[1] “I times J is 36”
[1] “I times J is 42”
[1] “I times J is 48”
[1] “I times J is 54”
[1] “I times J is 21”
[1] “I times J is 28”
[1] “I times J is 35”
[1] “I times J is 42”
[1] “I times J is 49”
[1] “I times J is 56”
[1] “I times J is 63”
[1] “I times J is 24”
[1] “I times J is 32”
[1] “I times J is 40”
[1] “I times J is 48”
[1] “I times J is 56”
[1] “I times J is 64”
[1] “I times J is 72”

In this nested forloop, I have two important segments. The I segment traverses through the numbers 2-8 while the J segment traverses through the numbers 3-9. However, the statements on their own are useless. The only line that really matters is the output line-"I times J is" , i*j. This line will print out the product of i and j.

OK, so that isn’t as simple as it looks. That is because the loop will traverse through every element of the I and J statements. In other words, the products of every element in the I statement and every element in the J statement will be displayed. For instance, the answer to 2*3 will be displayed, followed by 2*4, 2*5, all the way up to 2*9. Then all of the products from 3*3 to 3*9 will be displayed, and so forth, until you hit the 8 range (meaning from 8*3 to 8*9).

Now let’s create a while loop:

And here is the output (it was too long to fit on the same screenshot as the loop):

In this loop, I use 1902 as a starting point and 2018 as a stopping point. For each iteration, num will increase by 4 (starting from 1902) until 2018 is reached. In case you are wondering where I’m going with this, I’m printing out every even-numbered non-leap year between 1902 and 2018 inclusive.

  • Unfortunately, R doesn’t recognize increment/decrement symbols like ++, --, +=, -=, /=, *= the way Java does. So you’ll just have to increment/decrement in long form, as I did with the num <- num + 4 line.

Unlike for loops between Java and R, while loops between Java and R are very similar. Here’s the R loop for this program:

num <- 1902

while (num <= 2018)

{

print (num)

num <- num + 4

}

And here’s a Java whileloop that will do the exact same thing as the R loop:

num = 1902;

while (num <= 2018)

{

System.out.println(num)

num += 4;

}

One of the similarities between the two while loops are the parameters of the loop. In both loops, the lone parameter is what I’d like to call the running condition, which is the condition that tells the loop that while that condition is true, keep the loop running. In both cases, the running condition is num <= 2018.

The differences between the two loops are related to the difference in functions between Java and R. For instance, Java output requires System.out.printlnwhile R output simply requires print(or print(paste()) for outputs with strings). The other main difference is how to denote incrementing/decrementing in the loop, which I already discussed earlier in this post.

The third type of R loop is the repeat; this is the loop that is exclusive to R (just as the do-while loop is exclusive to Java). In R, a repeat loop is similar to a while loop in the sense that both loops have a stop condition (which is the condition that stops the loop from running). However, in while loops, the stop condition also functions as the running condition. For instance, the statement num <= 2018acts as both a running condition and a stop condition, since it tells the loop to keep running as long as num is less than or equal to 2018 but it also tells the loop to stop running as soon as 2018 (or the closest number to it) is reached.

Repeat loops don’t have a running condition per se, since they can be infinite. As a result, including a stop condition is totally optional. However, if you wish to include a stop condition, write an ifstatement (they’re formatted just like Java if statements) ending with the word break, which indicates that the loop will stop if the if statement condition is met.

Here’s an example of a repeat loop with a breakclause:

In this loop, I start with num <- 5 just outside the loop. Once I get inside the loop, numkeeps getting multiplied by 2 until a number that is either greater than or equal to 1000 is reached. All of the products of num * 2 are printed, and the last output is 1280, which is 640*2.

  • Had I not included a breakstatement, this loop would have gone on and on. Inf would be displayed after a certain point to denote that the loop would be infinite.

Thanks for reading,

Michael

Leave a ReplyCancel reply