If Else in R Programming Language

Our first example demonstrates the use of if/else statements in R. Here’s the full source code:

# Here's a basic example.
if (7 %% 2 == 0) {
  print("7 is even")
} else {
  print("7 is odd")
}

# You can have an if statement without an else.
if (8 %% 4 == 0) {
  print("8 is divisible by 4")
}

# Logical operators like && and || are often useful in conditions.
if (8 %% 2 == 0 || 7 %% 2 == 0) {
  print("either 8 or 7 are even")
}

# In R, we can use ifelse() for simple conditional statements.
num <- 9
result <- ifelse(num < 0, paste(num, "is negative"),
                 ifelse(num < 10, paste(num, "has 1 digit"),
                        paste(num, "has multiple digits")))
print(result)

To run the program, save the code in a file (e.g., if_else.R) and use the Rscript command:

$ Rscript if_else.R
[1] "7 is odd"
[1] "8 is divisible by 4"
[1] "either 8 or 7 are even"
[1] "9 has 1 digit"

Note that in R:

  1. We use %% for the modulo operation.
  2. The print() function is used instead of fmt.Println().
  3. R doesn’t have a direct equivalent to Go’s ability to declare and initialize a variable in the if statement. Instead, we declare the variable before the if statement.
  4. R provides the ifelse() function, which is similar to the ternary operator in other languages. It can be nested for multiple conditions.
  5. In R, you don’t need parentheses around conditions, but they are often used for clarity. Curly braces {} are required for multi-line blocks.

R also provides the switch() function for more complex conditional execution, which we’ll explore in the next example.