## Relational operators

- > greater than
- < less than
- >= greater than or equal to
- <= less than or equal to
- != not equal to
- == equal to

Above is a reminder of the relational operators used in R. These can be used to make element-wise comparisons of vectors where one vector is a multiple of the other. Look closely at the comparisons between vectors a and c to understand how R is iterating over a when comparing it to the elements of c.

```
Input:
a <- c(2,8,4)
b <- c(4,9,2)
c <- c(3,5,7,3,2,6)
```

```
```

```
a > b
b != a
a <= c
c <= a
Output:
FALSE FALSE TRUE
TRUE TRUE TRUE
TRUE FALSE TRUE TRUE FALSE TRUE
FALSE TRUE FALSE FALSE TRUE FALSE
```

```
```

Relational operators are often used in if statements to make a comparison between two elements then do something based on the outcome of that comparison. The example below demonstrates the syntax used in an if statement in R. The R language does not rely on indents or even carriage returns. If you wrote the if statement below on a single line it would work but would be horrible to read. The standard formatting convention for if statements is shown below.

```
Input:
x <- 3
y <- 5
if (x < y){
z <- x - y
}else{
z <- x + y
}
print(z)
Output:
[1] -2
```

```
```

## Logical operators

- ! logical NOT
- & element-wise logical AND
- && logical AND
- | element-wise logical OR
- || logical OR

The standard logical operators AND, OR, NOT are shown above. These are most commonly used in conjunction with relational comparison statements to make multiple comparisons to form a conditional if statement two examples of which can be seen below. It is good practice to account for all possible outcomes within an if statement. Any combination of circumstances for which there is no explicit conditional comparison are captured by the final else statement.

```
Input:
if (y > x && x > z){
print('z is lowest and y is highest')
}else if (x > y && y > z ){
print('x is highest and z is lowest')
}else if (z > x && x > y){
print('z is highest and y is lowest')
}else{
print('try another combination of comparisons')
}
Output:
[1] "z is lowest and y is highest"
```

```
```

```
Input:
if (y <= x || y >= z){
print(y)
}
Output:
[1] 5
```

```
```

You may have noticed that there are two different variants of the AND and OR operators.

In the example above we have used the double && and ||. These are used for comparing single values.

The element-wise AND and OR operators & and | are used to compare more than one value as the condition, for example:

```
Input:
(a > 1) & (a <= 5)
Output:
[1] 1 2 3 4 5 6
FALSE TRUE TRUE TRUE TRUE FALSE
```

```
```