Get startedGet started for free

Relational operators

1. Relational operators

When you want to make comparisons in your data, you will need relational operators.

2. A relational example

These let us take simple comparisons and program that logic to create more complex models. For example, was the stock price today less than yesterday? From a mathematics class, you might know that this symbol is used for less than in inequalities. It is also used in computer science as a relational operator to represent this type of logic. Comparing today and yesterday using the less than sign results in the logical, TRUE, because today was less than yesterday. If this was not true, then it would have returned FALSE.

3. Relational operators

Here is a table of the relational operators used in R. A few of them require some explanation. The operator for testing equality is two equal signs, not one.

4. Relational operators

This is a common mistake, and comes from the fact that 1 equal sign is an alternative way to perform assignment,

5. Relational operators

besides using an arrow. The operator for not equal will

6. Relational operators

return TRUE if two objects are not the same. The exclamation point in not equal is a standard computer science way of saying "not".

7. Relational operators

Let's look at a few more examples.

8. Relational operator examples

Here the value of 1 is assigned to a variable. When you perform the equality comparison, since the logical TRUE as a numeric is just the value of 1, this returns TRUE. Comparisons can also be made with vectors. Here each element of apple stock is compared against 121 and the appropriate logical value is returned. Notice that you did not have to have a vector of 121's of the same length as apple to make this comparison work. R recycles the 121 and checks it against each number in apple.

9. Let's practice!

In the next few you exercises, you will practice with these relational operators. Let's get started!