🤠Conditional Statement

if statement

An "if statement" is written with the if keyword, and it is used to specify a block of code to be executed if a condition is TRUE:

if (condition){
    # Statements
    }

else if Statement

The else if keyword is R's way of saying "if the previous conditions were not true, then try this condition".

NOTE: We can add as many else if condition as we need.

if (condition){
    # Statements
} else if (condition_2){
    # Statements_2
} else if (condition_3){
    # Statements_3
} ## Add as much "else if" as you need.

else Statement

The else keyword catches anything that isn't caught by the preceding conditions:

if (condition){
    # Statements
} else if (condition_2){
    # Statements_2
} else {
    # Last Statement
}

You can also use else without else if:

if (condition){
    # Statements
} else {
    # Last Statement
}

Nested if Statement

You can also have if statements inside if statements, this is called nested if statements.

if (condition){
  if (condition2){
    # Statement
  }
  else {
    # Statement2
  }
}
else {
  # Statement3
}

switch case Statement

Switch case statements are a substitute for long if statements that compare a variable to several integral values. switch case in R is a multiway branch statement. It allows a variable to be tested for equality against a list of values.

The switch statement follows the approach of mapping and searching over a list of values. If there is more than one match for a specific value, then the switch statement will return the first match found of the value matched with the expression.

# Simple syntax
switch(expression, case1, case2, case3....)

# Syntax in Details
switch (expression,
        "case 1" = Execute when the expression result matches case 1,
        "case 2" = Execute when the expression result matches case 2,
        "case 3" = When the expression result matches case 3, Execute these,
        ....
        ....
        "case N" = When the expression result matches case N, Execute these lines,
        Default Statements
)

Here, the expression is matched with the list of values and the corresponding value is returned.

  • The expression value should be either integer or characters (We can write the expression as n/2 also, but the result should be an integer or convertible integer).

  • An R Switch statement allows us to add a default statement. The default statements will be executed if the Expression value or the Index_Position does not match any of the cases.

  • The first matching statement will be returned if there is more than one match.

Flow Chart of switch case statement. Source

Sources

The sources of the contents on this page are:

Last updated