
In our previous example, where 15 wins allowed us to make the playoffs, let's add an if-else conditional. Adding an if-else statement into our while loop is the same as adding it to our for loop. To do this, we'll need to add an if-else statement into our while loop. Now that we've printed the status of the team when they don't have enough wins, we'll add a feature tthat indicates when they do make the playoffs. Using an if-else statement within a while loop Let's write our first while loop, counting red dragon wins!
Notice, that we continuously add 1 to the win total, so eventually, the win < 10 condition will return FALSE. Our loop will stop running when wins hits 10. If we were to write a loop for the following code:
#Rstudio ifelse code#
code block: This is the expression that's evaluated. See variables naming conventions in the first course for valid variable names. value: This is an iterator variable you use to refer to each value in the sequence. For example, this could be a vector of numbers c(1,2,3,4,5). However, if there are no more values left in the sequence, this will return FALSE and exit the loop. In this diagram, for each value in the sequence, the loop will execute the code block. A for loop repeats a chunk of code, multiple times for each element within an object: Instead, we can perform the same action using a for loop. Writing the results using if-else statements can work, but if our matches list contains 100 matches, it would be extremely cumbersome to write out each statement. Indexing with will return a list object, not the value. Keep in mind-we're using ] when indexing, since we want to return the single value, not the value with the list object.