Back

Conditional statements in R programming language

In R programming, conditional statements allow you to control the flow of your code based on certain conditions. The most commonly used conditional statements in R are:

1. if statement: The if statement allows you to execute a block of code only if a certain condition is true. The basic syntax is as follows:

if (condition) {
  # code to be executed if condition is true
}

For example, the following code checks whether a variable x is greater than 10, and if so, prints a message:

x <- 12

if (x > 10) {
  print("x is greater than 10")
}

2. if-else statement: The if-else statement allows you to execute one block of code if a condition is true, and another block of code if the condition is false. The basic syntax is as follows:

if (condition) {
  # code to be executed if condition is true
} else {
  # code to be executed if condition is false
}

For example, the following code checks whether a variable x is greater than 10, and if so, prints a message; otherwise, it prints a different message:

x <- 8
if (x > 10) {
  print("x is greater than 10")
} else {
  print("x is less than or equal to 10")
}

3. if-else if-else statement: The if-else if-else statement allows you to check multiple conditions and execute different blocks of code based on those conditions. The basic syntax is as follows:

if (condition1) {
  # code to be executed if condition1 is true
} else if (condition2) {
  # code to be executed if condition1 is false and condition2 is true
} else {
  # code to be executed if all conditions are false
}

For example, the following code checks whether a variable x is greater than 10, equal to 10, or less than 10, and prints a different message for each case:

x <- 8

if (x > 10) {
  print("x is greater than 10")
} else if (x == 10) {
  print("x is equal to 10")
} else {
  print("x is less than 10")
}

These conditional statements can be combined and nested to create more complex control structures. They are an essential tool for programming in R, allowing you to create code that can respond to different situations and conditions.

Change and run these commands yourself in this online R programming tool here

r programmingconditionalr onlineifelse ifelse

Latest Post

Information retrieval – Searching of text using Elasticsearch

Information retrieval is the process of obtaining relevant information resources from the collection of resources relevant to information need.

Learn more
© 2023 www.lamadly.com