Write a while loop

Let’s get you started with building a while loop from the ground up. Have another look at its recipe:

while (condition) { expr } Remember that the condition part of this recipe should become FALSE at some point during the execution. Otherwise, the while loop will go on indefinitely. In DataCamp’s learning interface, your session will be disconnected in this case.

Have a look at the code on the right; it initializes the speed variables and already provides a while loop template to get you started.

INSTRUCTIONS Code a while loop with the following characteristics:

The condition of the while loop should check if speed is higher than 30. Inside the body of the while loop, print out “Slow down!”. Inside the body of the while loop, decrease the speed by 7 units. This step is crucial; otherwise your while loop will never stop.

HINT You have to define the speed variable before you can use it in a while loop; initialize it to 64. Make sure that you decrease the speed variable at every execution of the loop’s code: speed <- speed - 7.

eyJsYW5ndWFnZSI6InIiLCJzYW1wbGUiOiIjIEluaXRpYWxpemUgdGhlIHNwZWVkIHZhcmlhYmxlXG5zcGVlZCA8LSA2NFxuXG4jIENvZGUgdGhlIHdoaWxlIGxvb3BcbndoaWxlICggKSB7XG4gIFxuICBcbn1cblxuIyBQcmludCBvdXQgdGhlIHNwZWVkIHZhcmlhYmxlXG5zcGVlZCIsInNvbHV0aW9uIjoiIyBJbml0aWFsaXplIHRoZSBzcGVlZCB2YXJpYWJsZVxuc3BlZWQgPC0gNjRcblxuIyBDb2RlIHRoZSB3aGlsZSBsb29wXG53aGlsZSAoc3BlZWQgPiAzMCkge1xuICBwcmludChcIlNsb3cgZG93biFcIilcbiAgc3BlZWQgPC0gc3BlZWQgLSA3XG59XG5cbiMgUHJpbnQgb3V0IHRoZSBzcGVlZCB2YXJpYWJsZVxuc3BlZWQifQ==

Throw in more conditionals

In the previous exercise, you simulated the interaction between a driver and a driver’s assistant: When the speed was too high, “Slow down!” got printed out to the console, resulting in a decrease of your speed by 7 units.

There are several ways in which you could make your driver’s assistant more advanced. For example, the assistant could give you different messages based on your speed or provide you with a current speed at a given moment.

A while loop similar to the one you’ve coded in the previous exercise is already available in the editor. It prints out your current speed, but there’s no code that decreases the speed variable yet, which is pretty dangerous. Can you make the appropriate changes?

INSTRUCTIONS If the speed is greater than 48, have R print out “Slow down big time!”, and decrease the speed by 11. Otherwise, have R simply print out “Slow down!”, and decrease the speed by 6.

HINT The if part inside the while loop should be:

if (speed > 48) { print(“Slow down big time!”) speed <- speed - 11 } Can you finish things by adding the appropriate code for the else part?

If the session keeps timing out and throwing an error, you are probably stuck in an infinite loop! Make sure that speed eventually decreases below 30.

eyJsYW5ndWFnZSI6InIiLCJzYW1wbGUiOiIjIEluaXRpYWxpemUgdGhlIHNwZWVkIHZhcmlhYmxlXG5zcGVlZCA8LSA2NFxuXG4jIEV4dGVuZC9hZGFwdCB0aGUgd2hpbGUgbG9vcFxud2hpbGUgKHNwZWVkID4gMzApIHtcbiAgcHJpbnQocGFzdGUoXCJZb3VyIHNwZWVkIGlzXCIsc3BlZWQpKVxuICBpZiAoICkge1xuICAgIFxuICAgIFxuICB9IGVsc2Uge1xuICAgIFxuICAgIFxuICB9XG59Iiwic29sdXRpb24iOiIjIEluaXRpYWxpemUgdGhlIHNwZWVkIHZhcmlhYmxlXG5zcGVlZCA8LSA2NFxuXG4jIEV4dGVuZC9hZGFwdCB0aGUgd2hpbGUgbG9vcFxud2hpbGUgKHNwZWVkID4gMzApIHtcbiAgcHJpbnQocGFzdGUoXCJZb3VyIHNwZWVkIGlzXCIsIHNwZWVkKSlcbiAgaWYgKHNwZWVkID4gNDgpIHtcbiAgICBwcmludChcIlNsb3cgZG93biBiaWcgdGltZSFcIilcbiAgICBzcGVlZCA8LSBzcGVlZCAtIDExXG4gIH0gZWxzZSB7XG4gICAgcHJpbnQoXCJTbG93IGRvd24hXCIpXG4gICAgc3BlZWQgPC0gc3BlZWQgLSA2XG4gIH1cbn0ifQ==

Stop the while loop: break

There are some very rare situations in which severe speeding is necessary: what if a hurricane is approaching and you have to get away as quickly as possible? You don’t want the driver’s assistant sending you speeding notifications in that scenario, right?

This seems like a great opportunity to include the break statement in the while loop you’ve been working on. Remember that the break statement is a control statement. When R encounters it, the while loop is abandoned completely.

INSTRUCTIONS

Adapt the while loop such that it is abandoned when the speed of the vehicle is greater than 80. This time, the speed variable has been initialized to 88; keep it that way.

HINT Use if (speed > 80) in combination with the break statement.

eyJsYW5ndWFnZSI6InIiLCJzYW1wbGUiOiIjIEluaXRpYWxpemUgdGhlIHNwZWVkIHZhcmlhYmxlXG5zcGVlZCA8LSA4OFxuXG53aGlsZSAoc3BlZWQgPiAzMCkge1xuICBwcmludChwYXN0ZShcIllvdXIgc3BlZWQgaXNcIiwgc3BlZWQpKVxuICBcbiAgIyBCcmVhayB0aGUgd2hpbGUgbG9vcCB3aGVuIHNwZWVkIGV4Y2VlZHMgODBcbiAgaWYgKCApIHtcbiAgICBcbiAgfVxuICBcbiAgaWYgKHNwZWVkID4gNDgpIHtcbiAgICBwcmludChcIlNsb3cgZG93biBiaWcgdGltZSFcIilcbiAgICBzcGVlZCA8LSBzcGVlZCAtIDExIiwic29sdXRpb24iOiIjIEluaXRpYWxpemUgdGhlIHNwZWVkIHZhcmlhYmxlXG5zcGVlZCA8LSA4OFxuXG53aGlsZSAoc3BlZWQgPiAzMCkge1xuICBwcmludChwYXN0ZShcIllvdXIgc3BlZWQgaXNcIiwgc3BlZWQpKVxuICBcbiAgIyBCcmVhayB0aGUgd2hpbGUgbG9vcCB3aGVuIHNwZWVkIGV4Y2VlZHMgODBcbiAgaWYgKCBzcGVlZCA+IDgwKSB7XG4gICAgYnJlYWtcbiAgfVxuICBcbiAgaWYgKHNwZWVkID4gNDgpIHtcbiAgICBwcmludChcIlNsb3cgZG93biBiaWcgdGltZSFcIilcbiAgICBzcGVlZCA8LSBzcGVlZCAtIDExXG4gIH0gZWxzZSB7XG4gICAgcHJpbnQoXCJTbG93IGRvd24hXCIpXG4gICAgc3BlZWQgPC0gc3BlZWQgLSA2XG4gIH1cbn0ifQ==

Now that you’ve correctly solved this exercise, feel free to play around with different values of speed to see how the while loop handles the different cases.

uild a while loop from scratch The previous exercises guided you through developing a pretty advanced while loop, containing a break statement and different messages and updates as determined by control flow constructs. If you manage to solve this comprehensive exercise using a while loop, you’re totally ready for the next topic: the for loop.

INSTRUCTIONS Finish the while loop so that it:

prints out the triple of i, so 3 * i, at each run. is abandoned with a break if the triple of i is divisible by 8, but still prints out this triple before breaking. Show Answer (-70 XP) HINT To check if the triple of i is divisible by 8, use the condition (i * 3) %% 8 == 0. The execution of %% has priority over * so you have to use parentheses to execute the multiplication first.

eyJsYW5ndWFnZSI6InIiLCJzYW1wbGUiOiIjIEluaXRpYWxpemUgaSBhcyAxIFxuaSA8LSAxXG5cbiMgQ29kZSB0aGUgd2hpbGUgbG9vcFxud2hpbGUgKGkgPD0gMTApIHtcbiAgcHJpbnQoX19fKVxuICBpZiAoIF9fXyApIHtcbiAgICBcbiAgfVxuICBpIDwtIGkgKyAxXG59Iiwic29sdXRpb24iOiIjIEluaXRpYWxpemUgaSBhcyAxIFxuaSA8LSAxXG5cbiMgQ29kZSB0aGUgd2hpbGUgbG9vcFxud2hpbGUgKGkgPD0gMTApIHtcbiAgcHJpbnQoMyAqIGkpXG4gIGlmICggKDMgKiBpKSAlJSA4ID09IDAgICkge1xuICAgIHByaW50KDMgKiBpKVxuICAgIGJyZWFrXG4gIH1cbiAgaSA8LSBpICsgMVxufSJ9

Loop over a vector

In the previous video, Filip told you about two different strategies for using the for loop. To refresh your memory, consider the following loops that are equivalent in R:

primes <- c(2, 3, 5, 7, 11, 13)

loop version 1 for (p in primes) { print(p) }

loop version 2 for (i in 1:length(primes)) { print(primes[i]) } Remember our linkedin vector? It’s a vector that contains the number of views your LinkedIn profile had in the last seven days. The linkedin vector has already been defined in the editor on the right so that you can fully focus on the instructions!

INSTRUCTIONS

Write a for loop that iterates over all the elements of linkedin and prints out every element separately. Do this in two ways: using the loop version 1 and the loop version 2 in the example code above.

HINT Copy the two loop versions from the example code chunk to the editor and change the variable names.

eyJsYW5ndWFnZSI6InIiLCJzYW1wbGUiOiIjIFRoZSBsaW5rZWRpbiB2ZWN0b3IgaGFzIGFscmVhZHkgYmVlbiBkZWZpbmVkIGZvciB5b3VcbmxpbmtlZGluIDwtIGMoMTYsIDksIDEzLCA1LCAyLCAxNywgMTQpXG5cbiMgTG9vcCB2ZXJzaW9uIDFcblxuXG5cblxuIyBMb29wIHZlcnNpb24gMiIsInNvbHV0aW9uIjoiIyBUaGUgbGlua2VkaW4gdmVjdG9yIGhhcyBhbHJlYWR5IGJlZW4gZGVmaW5lZCBmb3IgeW91XG5saW5rZWRpbiA8LSBjKDE2LCA5LCAxMywgNSwgMiwgMTcsIDE0KVxuXG4jIExvb3AgdmVyc2lvbiAxXG5mb3IgKGxpbiBpbiBsaW5rZWRpbikge1xuICBwcmludChsaW4pXG59XG5cbiMgTG9vcCB2ZXJzaW9uIDJcbmZvcihpIGluIDE6bGVuZ3RoKGxpbmtlZGluKSl7XG4gIHByaW50KGxpbmtlZGluW2ldKVxuICB9In0=

Loop over a list

Looping over a list is just as easy and convenient as looping over a vector. There are again two different approaches here:

primes_list <- list(2, 3, 5, 7, 11, 13)

loop version 1 for (p in primes_list) { print(p) }

loop version 2 for (i in 1:length(primes_list)) { print(primes_list[[i]]) } Notice that you need double square brackets - [[ ]] - to select the list elements in loop version 2.

Suppose you have a list of all sorts of information on New York City: its population size, the names of the boroughs, and whether it is the capital of the United States. We’ve already prepared a list nyc with all this information in the editor (source: Wikipedia).

INSTRUCTIONS As in the previous exercise, loop over the nyc list in two different ways to print its elements:

Loop directly over the nyc list (loop version 1). Define a looping index and do subsetting using double brackets (loop version 2).

HINT The start of the first loop could be for (info in nyc); in this case, you can use info to do the printout in the body of the for loop. The start of the second for loop could be for (i in 1:length(nyc)); in this case, you can use nyc[[i]] to do the printout in the body of the for loop.

eyJsYW5ndWFnZSI6InIiLCJzYW1wbGUiOiIjIFRoZSBueWMgbGlzdCBpcyBhbHJlYWR5IHNwZWNpZmllZFxubnljIDwtIGxpc3QocG9wID0gODQwNTgzNywgXG4gICAgICAgICAgICBib3JvdWdocyA9IGMoXCJNYW5oYXR0YW5cIiwgXCJCcm9ueFwiLCBcIkJyb29rbHluXCIsIFwiUXVlZW5zXCIsIFwiU3RhdGVuIElzbGFuZFwiKSwgXG4gICAgICAgICAgICBjYXBpdGFsID0gRkFMU0UpXG5cbiMgTG9vcCB2ZXJzaW9uIDFcblxuXG5cblxuIyBMb29wIHZlcnNpb24gMiIsInNvbHV0aW9uIjoiIyBUaGUgbnljIGxpc3QgaXMgYWxyZWFkeSBzcGVjaWZpZWRcbm55YyA8LSBsaXN0KHBvcCA9IDg0MDU4MzcsIFxuICAgICAgICAgICAgYm9yb3VnaHMgPSBjKFwiTWFuaGF0dGFuXCIsIFwiQnJvbnhcIiwgXCJCcm9va2x5blwiLCBcIlF1ZWVuc1wiLCBcIlN0YXRlbiBJc2xhbmRcIiksIFxuICAgICAgICAgICAgY2FwaXRhbCA9IEZBTFNFKVxuXG4jIExvb3AgdmVyc2lvbiAxXG5mb3IobiBpbiBueWMpe1xuICBwcmludChuKVxufVxuXG4jIExvb3AgdmVyc2lvbiAyXG5mb3IoaSBpbiAxOmxlbmd0aChueWMpKXtcbiAgcHJpbnQobnljW1tpXV0pXG59In0=

Loop over a matrix

In your workspace, there’s a matrix ttt, that represents the status of a tic-tac-toe game. It contains the values “X”, “O” and “NA”. Print out ttt in the console so you can have a closer look. On row 1 and column 1, there’s “O”, while on row 3 and column 2 there’s “NA”.

To solve this exercise, you’ll need a for loop inside a for loop, often called a nested loop. Doing this in R is a breeze! Simply use the following recipe:

for (var1 in seq1) { for (var2 in seq2) { expr } } INSTRUCTIONS Finish the nested for loops to go over the elements in ttt:

The outer loop should loop over the rows, with loop index i (use 1:nrow(ttt)). The inner loop should loop over the columns, with loop index j (use 1:ncol(ttt)). Inside the inner loop, make use of print() and paste() to print out information in the following format: “On row i and column j the board contains x”, where x is the value on that position. HINT For the outer loop, use for (i in 1:nrow(ttt)). For the inner loop, use for (j in 1:ncol(ttt)). Inside the inner loop, use this expression to print the board info: print(paste(“On row”, i, “and column”, j, “the board contains”, ttt[i,j]))

eyJsYW5ndWFnZSI6InIiLCJwcmVfZXhlcmNpc2VfY29kZSI6InR0dDwtYXMubWF0cml4KGMoXCJvXCIsTkEsXCJYXCIsTkEsXCJPXCIsXCJPXCIsXCJYXCIsTkEsXCJYXCIpLCBucm93PTMsIGJ5cm93PVRSVUUpIiwic2FtcGxlIjoiIyBUaGUgdGljLXRhYy10b2UgbWF0cml4IHR0dCBoYXMgYWxyZWFkeSBiZWVuIGRlZmluZWQgZm9yIHlvdVxuXG4jIGRlZmluZSB0aGUgZG91YmxlIGZvciBsb29wXG5mb3IgKF9fXyBpbiBfX18pIHtcbiAgZm9yIChfX18gaW4gX19fKSB7XG4gICAgcHJpbnQoX19fKVxuICB9XG59Iiwic29sdXRpb24iOiIjIFRoZSB0aWMtdGFjLXRvZSBtYXRyaXggdHR0IGhhcyBhbHJlYWR5IGJlZW4gZGVmaW5lZCBmb3IgeW91XG5cbiMgZGVmaW5lIHRoZSBkb3VibGUgZm9yIGxvb3BcbmZvciAoaSBpbiAxOm5yb3codHR0KSkge1xuICBmb3IgKGogaW4gMTpuY29sKHR0dCkpIHtcbiAgICBwcmludChwYXN0ZShcIk9uIHJvd1wiLCBpLCBcImFuZCBjb2x1bW5cIiwgaiwgXCJ0aGUgYm9hcmQgY29udGFpbnNcIiwgdHR0W2ksal0pKVxuICB9XG59In0=

Mix it up with control flow

Let’s return to the LinkedIn profile views data, stored in a vector linkedin. In the first exercise on for loops you already did a simple printout of each element in this vector. A little more in-depth interpretation of this data wouldn’t hurt, right? Time to throw in some conditionals! As with the while loop, you can use the if and else statements inside the for loop.

INSTRUCTIONS

Add code to the for loop that loops over the elements of the linkedin vector:

If the vector element’s value exceeds 10, print out “You’re popular!”. If the vector element’s value does not exceed 10, print out “Be more visible!”

HINT The if part should be:

if (li > 10) { print(“You’re popular!”) } Can you add the else part?

eyJsYW5ndWFnZSI6InIiLCJzYW1wbGUiOiIjIFRoZSBsaW5rZWRpbiB2ZWN0b3IgaGFzIGFscmVhZHkgYmVlbiBkZWZpbmVkIGZvciB5b3VcbmxpbmtlZGluIDwtIGMoMTYsIDksIDEzLCA1LCAyLCAxNywgMTQpXG5cbiMgQ29kZSB0aGUgZm9yIGxvb3Agd2l0aCBjb25kaXRpb25hbHNcbmZvciAobGkgaW4gbGlua2VkaW4pIHtcbiAgaWYgKCApIHtcbiAgICBcbiAgfSBlbHNlIHtcbiAgICBcbiAgfVxuICBwcmludChsaSlcbn0iLCJzb2x1dGlvbiI6IiMgVGhlIGxpbmtlZGluIHZlY3RvciBoYXMgYWxyZWFkeSBiZWVuIGRlZmluZWQgZm9yIHlvdVxubGlua2VkaW4gPC0gYygxNiwgOSwgMTMsIDUsIDIsIDE3LCAxNClcblxuIyBDb2RlIHRoZSBmb3IgbG9vcCB3aXRoIGNvbmRpdGlvbmFsc1xuZm9yIChsaSBpbiBsaW5rZWRpbikge1xuICBpZiAoIGxpID4gMTApIHtcbiAgICBwcmludChcIllvdSdyZSBwb3B1bGFyIVwiKVxuICB9IGVsc2Uge1xuICAgIHByaW50KFwiQmUgbW9yZSB2aXNpYmxlIVwiKVxuICB9XG4gIHByaW50KGxpKVxufSJ9

In the next exercise, you’ll customize this for loop even further with break and next statements.

Next, you break it

In the editor on the right you’ll find a possible solution to the previous exercise. The code loops over the linkedin vector and prints out different messages depending on the values of li.

In this exercise, you will use the break and next statements:

The break statement abandons the active loop: the remaining code in the loop is skipped and the loop is not iterated over anymore. The next statement skips the remainder of the code in the loop, but continues the iteration. INSTRUCTIONS 70 XP Extend the for loop with two new, separate if tests in the editor as follows:

If the vector element’s value exceeds 16, print out “This is ridiculous, I’m outta here!” and have R abandon the for loop (break). If the value is lower than 5, print out “This is too embarrassing!” and fast-forward to the next iteration (next). Show Answer (-70 XP) HINT The first if statement you should add looks as follows:

if (li > 16) { print(“This is ridiculous, I’m outta here!”) break } Can you add a similar if statement that uses next?

eyJsYW5ndWFnZSI6InIiLCJzYW1wbGUiOiIjIFRoZSBsaW5rZWRpbiB2ZWN0b3IgaGFzIGFscmVhZHkgYmVlbiBkZWZpbmVkIGZvciB5b3VcbmxpbmtlZGluIDwtIGMoMTYsIDksIDEzLCA1LCAyLCAxNywgMTQpXG5cbiMgRXh0ZW5kIHRoZSBmb3IgbG9vcFxuZm9yIChsaSBpbiBsaW5rZWRpbikge1xuICBpZiAobGkgPiAxMCkge1xuICAgIHByaW50KFwiWW91J3JlIHBvcHVsYXIhXCIpXG4gIH0gZWxzZSB7XG4gICAgcHJpbnQoXCJCZSBtb3JlIHZpc2libGUhXCIpXG4gIH1cbiAgXG4gICMgQWRkIGlmIHN0YXRlbWVudCB3aXRoIGJyZWFrXG4gIFxuICBcbiAgIyBBZGQgaWYgc3RhdGVtZW50IHdpdGggbmV4dFxuICBcbiAgXG4gIHByaW50KGxpKVxufSIsInNvbHV0aW9uIjoiIyBUaGUgbGlua2VkaW4gdmVjdG9yIGhhcyBhbHJlYWR5IGJlZW4gZGVmaW5lZCBmb3IgeW91XG5saW5rZWRpbiA8LSBjKDE2LCA5LCAxMywgNSwgMiwgMTcsIDE0KVxuXG4jIEV4dGVuZCB0aGUgZm9yIGxvb3BcbmZvciAobGkgaW4gbGlua2VkaW4pIHtcbiAgaWYgKGxpID4gMTApIHtcbiAgICBwcmludChcIllvdSdyZSBwb3B1bGFyIVwiKVxuICB9IGVsc2Uge1xuICAgIHByaW50KFwiQmUgbW9yZSB2aXNpYmxlIVwiKVxuICB9XG4gIFxuICAjIEFkZCBpZiBzdGF0ZW1lbnQgd2l0aCBicmVha1xuICBpZiAobGkgPiAxNil7XG4gIHByaW50KFwiVGhpcyBpcyByaWRpY3Vsb3VzLCBJJ20gb3V0dGEgaGVyZSFcIilcbiAgfVxuICAjIEFkZCBpZiBzdGF0ZW1lbnQgd2l0aCBuZXh0XG4gIGlmIChsaSA8IDUpe1xuICAgIHByaW50KFwiVGhpcyBpcyB0b28gZW1iYXJyYXNzaW5nIVwiKVxuICAgIG5leHRcbiAgfVxuICBcbiAgcHJpbnQobGkpXG59In0=

Great. for, break, next? We name it, you can do it!

Build a for loop from scratch

This exercise will not introduce any new concepts on for loops.

In the editor on the right, we already went ahead and defined a variable rquote. This variable has been split up into a vector that contains separate letters and has been stored in a vector chars with the strsplit() function.

Can you write code that counts the number of r’s that come before the first u in rquote?

INSTRUCTIONS

Initialize the variable rcount, as 0. Finish the for loop: if char equals “r”, increase the value of rcount by 1. if char equals “u”, leave the for loop entirely with a break. Finally, print out the variable rcount to the console to see if your code is correct.

HINT To initialize the rcount variable, use rcount <- 0. You have to add two if tests to the for loop. The first one starts as if (char == “r”), the second as if (char == “u”).

eyJsYW5ndWFnZSI6InIiLCJzYW1wbGUiOiIjIFByZS1kZWZpbmVkIHZhcmlhYmxlc1xucnF1b3RlIDwtIFwicidzIGludGVybmFscyBhcmUgaXJyZWZ1dGFibHkgaW50cmlndWluZ1wiXG5jaGFycyA8LSBzdHJzcGxpdChycXVvdGUsIHNwbGl0ID0gXCJcIilbWzFdXVxuXG4jIEluaXRpYWxpemUgcmNvdW50XG5yY291bnQgPC0gXG5cbiMgRmluaXNoIHRoZSBmb3IgbG9vcFxuZm9yIChjaGFyIGluIGNoYXJzKSB7XG4gIFxuICBcbn1cblxuIyBQcmludCBvdXQgcmNvdW50Iiwic29sdXRpb24iOiIjIFByZS1kZWZpbmVkIHZhcmlhYmxlc1xucnF1b3RlIDwtIFwicidzIGludGVybmFscyBhcmUgaXJyZWZ1dGFibHkgaW50cmlndWluZ1wiXG5jaGFycyA8LSBzdHJzcGxpdChycXVvdGUsIHNwbGl0ID0gXCJcIilbWzFdXVxuXG4jIEluaXRpYWxpemUgcmNvdW50XG5yY291bnQgPC0gMFxuXG4jIEZpbmlzaCB0aGUgZm9yIGxvb3BcbmZvciAoY2hhciBpbiBjaGFycykge1xuICBpZihjaGFyID09IFwiclwiKVxucmNvdW50ID0gcmNvdW50ICsgMVxuaWYoY2hhciA9PSBcInVcIilcbiAgYnJlYWtcbn1cblxuIyBQcmludCBvdXQgcmNvdW50XG5wcmludChyY291bnQpIn0=

This exercise concludes the chapter on while and for loops.