R If Statement

An R if statement is used to execute a block of code only when a given condition is TRUE. It is one of the basic control structures in R and is commonly used for decision making in programs, scripts, and data analysis workflows.

For example, you can use an if statement to print a message only when a number is even, run a calculation only when a value is positive, or check whether two strings are equal before continuing with the next step.

How R if statement controls program flow

R If statement executes a set of statements based on a given condition. If the condition in If-statement evaluates to TRUE, then the statements in the If block execute, else not.

In this tutorial, we will learn about R If statement and how does this help in decision making with syntax, flow diagram and examples.

R if statement flow diagram

The flow diagram that shows the flow of execution for an if statement is given below.

R If statement - flow diagram

R if statement syntax

The syntax of R If statement is

</>
Copy
if (condition) {
     statement1
     statement2  . . .
     statementN
 }

The condition is any expression that evaluates to a boolean value. And if condition = TRUE, execution flow enters the block of If-statement, else it skips the statements’ execution in the block and continues with the statements after If-statement, if any.

In practice, the condition should produce a single logical value: TRUE or FALSE. Use comparison operators such as ==, !=, >, <, >=, and <= to build conditions.

R if statement condition rules: ==, <-, TRUE and FALSE

A common beginner mistake is confusing assignment with comparison. In R, <- is commonly used to assign a value to a variable, while == checks whether two values are equal.

OperatorUse in RExample
<-Assigns a valuea <- 6
=Can assign a value in many contexts, but <- is commonly preferred for assignment in R codea = 6
==Compares two valuesa == 6

Inside an if condition, use == when you want to test equality. For example, if (a == 6) checks whether a is equal to 6.

R if statement examples

In the following examples, we will go through different scenarios like if the If-condition is TRUE, or If-condition is FALSE; and some use cases where If-statement is used.

R if statement when condition is TRUE

In the following program, we will write an If-statement with condition that checks if the value in variable a is 6.

Example.R

</>
Copy
a <- 6

if (a == 6) {
  print ("Value in a is 6.")
}

print("End of program.")

Output

[1] "Value in a is 6."
[1] "End of program."

Since the condition a == 6 evaluates to TRUE, the code inside If block is executed.

R if statement when condition is FALSE

Now, let us take a value for a, say a = 10.

Example.R

</>
Copy
a <- 10

if (a == 6) {
  print ("Value in a is 6.")
}

print("End of program.")

Output

[1] "End of program."

Since a is 10, the condition a == 6 evaluates to FALSE. Therefore, the code inside If-block is not executed.

Check if number is even using R if statement

In this example, we use If-statement to check if a number is even. If n is the number, then If-condition could be n%%2 == 0.

Example.R

</>
Copy
n <- 10

if (n %% 2 == 0) {
  print ("Number is even.")
}

Output

[1] "Number is even."

The modulus operator %% gives the remainder after division. If n %% 2 is 0, the number is divisible by 2 and the condition becomes TRUE.

Check if strings are equal using R if statement

In this example, we use If-statement to check if two strings are equal. If str1 and str2 are the strings, then the condition to check if these two strings are equal is str1 == str2.

Example.R

</>
Copy
str1 <- "hello"
str2 <- "hello"

if (str1 == str2) {
  print ("The two strings are equal.")
}

Output

[1] "The two strings are equal."

The expression str1 == str2 returns TRUE because both strings contain the same text.

Use AND operator in R if statement condition

In this example, we check if given number is even and divisible by 3. Since the number has to satisfy both the conditions, we may join the condition using AND operator.

Example.R

</>
Copy
n <- 12

if ((n %% 2 == 0) && (n %% 3 == 0)) {
  print ("Number is even and divisible by 3.")
}

Output

[1] "Number is even and divisible by 3."

For a single if condition, && is usually preferred when you want a single logical result. It checks whether both conditions are TRUE. For vectorized comparisons, R also has &, but that is not the usual choice for a single control-flow condition.

Use NOT operator in R if statement condition

In this example, we check if given number is not even number. Since we have to check the negation of the condition that the number is even, we use NOT operator for the condition.

Example.R

</>
Copy
n <- 11

if (!(n %% 2 == 0)) {
  print ("Number is not even.")
}

Output

[1] "Number is not even."

The ! operator reverses the logical result. Here, n %% 2 == 0 is FALSE, so !(n %% 2 == 0) becomes TRUE.

R if else syntax for two-way decisions

Use if alone when you want to run code only for the TRUE case. Use if else when you want one block to run when the condition is TRUE and another block to run when the condition is FALSE.

</>
Copy
if (condition) {
  # runs when condition is TRUE
} else {
  # runs when condition is FALSE
}

Example of an if else statement in R:

</>
Copy
marks <- 72

if (marks >= 50) {
  print("Passed")
} else {
  print("Failed")
}

Output

[1] "Passed"

R else if syntax for multiple conditions

Use else if when more than two outcomes are possible. R checks the conditions from top to bottom and executes the first block whose condition is TRUE.

</>
Copy
if (condition1) {
  # runs when condition1 is TRUE
} else if (condition2) {
  # runs when condition2 is TRUE
} else {
  # runs when none of the above conditions is TRUE
}

Example of checking a score category using if, else if, and else:

</>
Copy
score <- 85

if (score >= 90) {
  print("Grade A")
} else if (score >= 75) {
  print("Grade B")
} else if (score >= 50) {
  print("Grade C")
} else {
  print("Needs improvement")
}

Output

[1] "Grade B"

Multiple conditions in R if statement with AND and OR

For a single if condition, use && for logical AND and || for logical OR. Use parentheses to make compound conditions easier to read.

</>
Copy
age <- 24
has_id <- TRUE

if ((age >= 18) && has_id) {
  print("Allowed")
}

Output

[1] "Allowed"

Use || when at least one condition should be true:

</>
Copy
day <- "Sunday"

if ((day == "Saturday") || (day == "Sunday")) {
  print("Weekend")
}

Output

[1] "Weekend"

Common mistakes with R if statement

The following mistakes are common when writing if statements in R:

  • Using = or <- instead of == when checking equality.
  • Writing a condition that returns multiple logical values instead of one clear TRUE or FALSE.
  • Forgetting braces when the block has more than one statement.
  • Placing else on a separate new line after a completed if block in a way that breaks parsing in interactive use.
  • Using & or | for scalar control flow when && or || is more suitable.

A readable if statement usually has a clear condition, braces around the code block, and meaningful variable names.

R if statement QA checklist

  • Does the condition evaluate to a single logical value, either TRUE or FALSE?
  • Is == used for equality comparison instead of assignment?
  • Are braces used around the statements that belong to the if block?
  • Are compound conditions grouped with parentheses for readability?
  • Is if else used when both TRUE and FALSE cases need separate actions?
  • Is else if used only when multiple ordered conditions are required?

FAQs on R if statement

What is an if statement in R?

An if statement in R is a control structure that runs a block of code only when its condition evaluates to TRUE. If the condition is FALSE, R skips the if block and continues with the next statement.

What is == in an R if condition?

In R, == is the equality comparison operator. It checks whether the value on the left is equal to the value on the right. For example, if (a == 6) checks whether a is equal to 6.

What is the difference between = and == in R?

In R, = can be used for assignment in many contexts, while == is used for comparison. In an if condition, use == when you want to test whether two values are equal.

How do you use if else in R with multiple conditions?

Use if with else if and else when there are multiple possible outcomes. R checks the conditions in order and executes the first block whose condition is TRUE.

Should I use && or & inside an R if statement?

For a normal if statement that needs one TRUE or FALSE result, use && for AND conditions. The & operator is vectorized and is mainly used when comparing vectors element by element.

Summary of R if statement decision making

In this R Tutorial, we learned about R If-statement, its syntax and how this if statement helps in decision making, with examples.