6.5 Use "if" statements to control program flow - Video Tutorials & Practice Problems
Video duration:
2m
Play a video:
<v Voiceover>Comparing</v> the value of two objects, particularly with if statements, is a critical part of programming. R offers a number of facilities for doing this, the most basic one is the if statement. But before we do that, let's look at some true/false tests. We can test if one equals one, and that returns true. Testing is one less than one, returns false because one is not less than one. However, one less than or equal to one, will return true because one is indeed less than or equal to one. Likewise, one is greater than, returns false. And one is greater than or equal to one, returns true, if it's done correctly. While white space is generally allowed in R between operands and variables, in something like a comparator, such as greater than or equal to, you need to have no spaces. When we run this, we get true. The way to test for inequality is to say one exclamation mark equals sign one. And this will be false because one is actually equal to one. So let's use an if statement to control the flow a program. Let's create a variable called to check, we'll assign it the value of one. Then we will say, if to check is equal to one, then print hello. So when we run this if statement, it prints hello. Now if we were to copy this statement here, and run it again, but this time, with to dot check equal to zero, nothing gets printed, because that if statement failed. Understanding if statements and how they can really structure and flow your program is incredibly important, because they really are the gatekeepers of the programming world.