R Operators
Operators compare values and combine logical values. Each comparison gives TRUE or FALSE.
Compare two numbers
This program compares 10 and 4 in four ways. Each print shows TRUE or FALSE.
a <- 10
b <- 4
print(a == b)
print(a != b)
print(a > b)
print(a < b)Include equal values
The first test checks whether 7 is at least 7. The second test checks whether 7 is at most 6.
a <- 7
print(a >= 7)
print(a <= 6)Flip and combine logic
The first print flips TRUE to its opposite. The next two prints combine pairs of logical values.
print(!TRUE)
print(TRUE & FALSE)
print(TRUE | FALSE)Single decision operators
This program combines two logical values in each print. The symbols make one decision from each pair.
print(TRUE && TRUE)
print(FALSE || FALSE)A trapped comparison
This print compares the number 1 with the text a. The comparison gives TRUE.
print(1 < "a")Example
score <- 85
print(score >= 80 & score < 90)Key points
- The symbol == tests whether two values are equal.
- The symbol != tests whether two values differ.
- The symbols < and > test which value is smaller or larger.
- The symbols <= and >= also count equal values as a pass.
- The symbol ! flips a logical value to its opposite.
- The symbols & and | combine two logical values.
- The symbols && and || also combine two logical values for one single decision.
In this example, both tests pass for a score of 85. The & symbol joins them into one TRUE result.
Note
Comparing a number with text turns the number into text, so 1 < "a" gives TRUE.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does print(5 == 5) show?