Site icon R-bloggers

R if…else

[This article was first published on R feed, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

R if Statement

The if statement is a conditional statement that allows you to provide conditions to execute a piece of code.

The syntax of if statement in R is:

if(test_expression) {
  # body of if statement
}

If the test_expression inside the if statement is TRUE, then the code inside the if block will be executed.


else Statement

You can use the else statement along with an if statement to specify code to be executed if the test_expression in if statement returns FALSE.

if(test_expression) {
  # block of code if condition is true
} else {
  # block of code if condition is false
}

Example 1: R if…else Statement

x <- 12

# check if x is positive or negative number
if (x > 0) {
  print("x is a positive number")
} else {
  print("x is a negative number")
}

Output

[1] "x is a positive number"

Here, since x > 0 evaluates to TRUE, the code inside the if block gets executed.


The if…else if…else Statement

If you want to test more than one condition, you can use the optional else if statement along with your if...else statements. The syntax is:

if(test_expression_1) {
  # code block 1
} else if (test_expression_2){
  # code block 2
} else {
  # code block 3
}

Here,


Example 2: R if…else if…else Statement

x <- 0

# check if x is positive or negative or zero
if (x > 0) {
  print("x is a positive number")
} else if (x < 0) {
  print("x is a negative number")
} else {
  print("x is zero")
}

Output

[1] "x is zero"

In this program, we have used an if...else if...else block to check whether x is a positive number, a negative number, or zero. Here,

Since x = 0, the else block is executed.


Nested if…else Statements

You can have nested if...else statements inside if...else blocks in R. This allows you to specify conditions inside conditions. For example,

x <- 20

# check if x is positive
if (x > 0) {

  # check if x is even or odd
  if (x %% 2 == 0) {
    print("x is a positive even number")
  } else {
    print("x is a positive odd number")
  }

# execute if x is not positive
} else {

  # check if x is even or odd
  if (x %% 2 == 0) {
    print("x is a negative even number")
  } else {
    print("x is a negative odd number")
  }
}

Output

[1] "x is a positive even number"

In this program,

To leave a comment for the author, please follow the link and comment on their blog: R feed.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.