Logical Operators
Overview
Logical operators are symbols that can be used within R to compare values or vectors of values.
Operator | Description |
---|---|
< |
less than |
⇐ |
less than or equal to |
> |
greater than |
>= |
greater than or equal to |
== |
equal to |
!= |
not equal to |
!x |
negation, not x |
x|y |
x OR y |
x&y |
x AND y |
Examples
Given a vector, vec
, get a vector of logical values indicating whether the values are greater than 5 (TRUE
), or not (FALSE
).
Solution
vec <- 1:10
vec > 5
[1] FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE
Given a vector, vec
, get a vector of logical values indicating whether the values are greater than or equal to 5 (TRUE
), or not (FALSE
).
Solution
vec <- 1:10
vec >= 5
[1] FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE TRUE
Given a vector, vec
, get a vector of logical values indicating whether the values are less than 5 (TRUE
), or not (FALSE
).
Solution
vec <- 1:10
vec < 5
[1] TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE
Given a vector, vec
, get a vector of logical values indicating whether the values are less than or equal to 5 (TRUE
), or not (FALSE
).
Solution
vec <- 1:10
vec <= 5
[1] TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE
Given a vector, vec
, get a vector of logical values indicating whether the values that are greater than 7 or less than or equal to 2 (TRUE
), or not (FALSE
).
Solution
vec <- 1:10
vec > 7 | vec <=2
[1] TRUE TRUE FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE
Given a vector, vec
, get a vector of logical values indicating whether the values that are greater than 3 and less than 6 (TRUE
), or not (FALSE
).
Solution
vec <- 1:10
vec > 3 & vec < 6
[1] FALSE FALSE FALSE TRUE TRUE FALSE FALSE FALSE FALSE FALSE
Given vectors vec1
and vec2
, get the values that are in vec1
that are also in vec2
.
Solution
vec1 <- c("this", "is", "a", "test")
vec2 <- c("this", "a", "exam")
vec1[vec1 %in% vec2]
[1] "this" "a"