Conditional Expression

Conditional expressions are one of the basic features of programming. They are used for what is called flow control. The most common conditional expression is the if-else statement. In R, we can actually perform quite a bit of data analysis without conditionals. However, they do come up occasionally, and you will need them once you start writing your own functions and packages.

Here is a very simple example showing the general structure of an if-else statement. The basic idea is to print the reciprocal of a unless a is 0:

a <- 0

if(a!=0){
  print(1/a)
} else{
  print("No reciprocal for 0.")
}
#> [1] "No reciprocal for 0."

Instruction

  • Fix the code to check whether the number is even number and print
# Create a variable x x <- 4 # Add condition to check x is an even number if (_______){ print("x is an even number.") } else{ print("x is not an even number.") } # Create a variable x x <- 4 # Add condition to check x is an even number if (x %% 2 == 0){ print("x is an even number.") } else{ print("x is not an even number.") } msg <- "Please see that objects are well-defined and correct." test_output_contains("if (x %% 2 == 0){ print(\"x is an even number.\") } else{ print(\"x is not an even number.\") }") success_msg("Great! Head over to the next exercise.")

Previous: 2-1 | Programming basics

Next: 2-3 | ifelse() function

Back to Main