# Conditional Statement

## <mark style="color:red;">`if`</mark> statement

An "<mark style="color:red;">`if`</mark> statement" is written with the <mark style="color:red;">`if`</mark> keyword, and it is used to specify a block of code to be executed if a condition is <mark style="color:red;">`TRUE`</mark>:

{% tabs %}
{% tab title="Syntax" %}

```r
if (condition){
    # Statements
    }
```

{% endtab %}

{% tab title="Example" %}

```
# Age of two people
adam <- 33
bob <- 45

# Run the if statement
if (bob > adam){
  print("bob is older than adam")
}
```

{% endtab %}
{% endtabs %}

<figure><img src="https://3681152927-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvUtrdiIkCrBX60yTgn1m%2Fuploads%2Fu0BGevCOnSU796GrhMq2%2Fif_statement.png?alt=media&#x26;token=29773146-2f20-40df-a0b1-3da480a8a492" alt=""><figcaption></figcaption></figure>

### <mark style="color:red;">`else if`</mark> Statement

The <mark style="color:red;">`else if`</mark> keyword is R's way of saying "if the previous conditions were not true, then try this condition".

NOTE: We can add as many <mark style="color:red;">`else if`</mark> condition as we need.

{% tabs %}
{% tab title="Syntax" %}

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

```

{% endtab %}

{% tab title="Example" %}

```r

# Age of two people
adam <- 33
bob <- 33

# Run the if statement
if (bob > adam){
  print("bob is older than adam")
} else if (bob == adam){
  print("They are both same age")
}
```

{% endtab %}
{% endtabs %}

<figure><img src="https://3681152927-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvUtrdiIkCrBX60yTgn1m%2Fuploads%2FkTZp8HmmSn4XdJHnVPRh%2Felse_if.png?alt=media&#x26;token=f1ba3991-dc80-4cfa-9d00-468c1dfa781c" alt=""><figcaption></figcaption></figure>

### <mark style="color:red;">`else`</mark> Statement

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

{% tabs %}
{% tab title="Syntax" %}

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

You can also use `else` without <mark style="color:red;">`else if`</mark>:

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

{% endtab %}

{% tab title="Example" %}

```r
a <- 200
b <- 33

if (b > a) {
  print("b is greater than a")
} else if (a == b) {
  print("a and b are equal")
} else {
  print("a is greater than b")
}
```

<mark style="color:green;">**Code Breakdown**</mark>:

In this example, <mark style="color:red;">**`a`**</mark> is greater than <mark style="color:red;">**`b`**</mark>, so the first condition is not true, also the <mark style="color:red;">`else if`</mark> condition is not true, so we go to the <mark style="color:red;">`else`</mark> condition and print to screen that "**a is greater than b**".
{% endtab %}
{% endtabs %}

<figure><img src="https://3681152927-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvUtrdiIkCrBX60yTgn1m%2Fuploads%2F04Q7BIjxIDvDk0OUQA0Q%2Fimage.png?alt=media&#x26;token=0227ebf7-d504-42e1-81bd-f3e546cd6ed2" alt=""><figcaption></figcaption></figure>

### Nested <mark style="color:red;">`if`</mark> Statement

You can also have <mark style="color:red;">`if`</mark> statements inside <mark style="color:red;">`if`</mark> statements, this is called ***nested*** <mark style="color:red;">`if`</mark> statements.

{% tabs %}
{% tab title="Syntax" %}

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

{% endtab %}

{% tab title="Example" %}

```r
x <- 40

if (x > 20) {
  print("Larger than 20")
  if (x %% 20 == 0) {
    print("and also an even number")
  } else {
    print("but odd number")
  }
} else {
  print("below 20.")
}
```

{% endtab %}
{% endtabs %}

## <mark style="color:red;">`switch case`</mark> Statement

**Switch case** statements are a substitute for long if statements that compare a variable to several integral values. <mark style="color:red;">`switch case`</mark> in R is a multiway branch statement. It allows a variable to be tested for equality against a list of values.

The <mark style="color:red;">`switch`</mark> 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.

{% tabs %}
{% tab title="Syntax" %}

```r
# 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.
  {% endtab %}

{% tab title="Example\_1" %}

```r
weekDay <- 3
switch(weekDay,
       '1' = print("Saturday"),
       '2' = print("Sunday"),
       '3' = print("Monday"),
       '4' = print("Tuesday"),
       '5' = print("Wednesday"),
       '6' = print("Thursday"),
       '7' = print("Friday"),
       print("Not a valid input")
)
```

<mark style="color:green;">**Code Breakdown**</mark>**:** Here,

* <mark style="color:red;">`weekDay`</mark> : is the expression that takes the input.
* Our code will show output based on the input, when input matches with a **case** inside the code, it will print related output.
* If the input doesn't match with any **case** inside the code, it will print the **default case**. In this code default **case** is <mark style="color:red;">`print("Not a valid input")`</mark>.
  {% endtab %}

{% tab title="Example\_2" %}

```r
cal1 = 6
cal2 = 7
cal3 = "p"
switch(cal3,
  "a"= cat("Addition =", cal1 + cal2),
  "d"= cat("Subtraction =", cal1 - cal2),
  "r"= cat("Division = ", cal1 / cal2),
  "s"= cat("Multiplication =", cal1 * cal2),
  "m"= cat("Modulus =", cal1 %% cal2),
  "p"= cat("Power =", cal1 ^ cal2)
)
```

<mark style="color:green;">**Code Breakdown**</mark>**:** Here,

The `cat()` function in R is used to concatenate objects and print them to the console or a file. The basic syntax of the function is `cat(..., file = "", sep = " ", append = FALSE)`, where `...` represents the objects to concatenate, `file` is the file name to send output to, `sep` is the separator to use between objects, and `append` is a logical value indicating whether to append output to an existing file or create a new file. The function can be used in different ways, such as concatenating strings with a specified separator, outputting results to a file, and printing character strings in a readable format. To save the output of the `cat()` function as a value in R, it is recommended to use the `paste()` function instead.
{% endtab %}
{% endtabs %}

<figure><img src="https://3681152927-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvUtrdiIkCrBX60yTgn1m%2Fuploads%2FrYwrQMoE9UUogobMy1Lv%2Fimage.png?alt=media&#x26;token=bd3d0595-bcdb-4c9f-a3a5-fe1005ca5041" alt=""><figcaption><p>Flow Chart of switch case statement. <a href="https://contribute.geeksforgeeks.org/wp-content/uploads/switch.png">Source</a> </p></figcaption></figure>

## Sources

The sources of the contents on this page are:

1. <https://www.w3schools.com/r/r_if_else.asp>
2. <https://www.w3schools.com/r/r_if_else_nested.asp>
3. <https://www.w3schools.com/r/r_if_else_andor.asp>
4. <https://www.tutorialgateway.org/r-switch-statement/>
5. [R for Data Science Full Course | Data Science Training | Edureka](https://youtu.be/ckdHNu4kfL0?t=2605)
