O'Reilly logo

Data Analysis with R - Second Edition by Tony Fischetti

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Flow of control

The last topic in this section will be flow of control constructs.

The most basic flow of control construct is the if statement. The argument to an if statement (what goes between the parentheses) is an expression that returns a logical value. The block of code following the if statement gets executed only if the expression yields TRUE:

   > if(2 + 2 == 4) 
   +   print("very good") 
  [1] "very good" 
   > if(2 + 2 == 5) 
   +    print("all hail to the thief") 

It is possible to execute more than one statement if an if condition is triggered; you just have to use curly brackets ({}) to contain the statements:

   > if((4/2==2) && (2*2==4)){ 
   +    print("four divided by two is two...") 
   +    print("and two times two is four") 
   + } 
  [1] "four divided by two ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required