Section 14 R Atomic Class: Logical

  • A logical vector is TRUE or FALSE

  • It is the R representation of Boolean data

  • The logical vector is very helpful for comparisons

  • A logical vector is created by typing TRUE or FALSE (uppercase without the quote marks)

  • R also assume T and F as shorthand for TRUE or FALSE

  • Enclosing TRUE or FALSE by quotes will render it to a character vector

  • Function to identify the object type: class, typeof, mode

  • Other functions to check the object type as logical: is.logical

14.1 Examples

x <- TRUE
class(x)
typeof(x)
is.logical(x)

y <- T
class(y)

z <- F
class(z)
is.logical(z)

14.2 Examples: comparison

  • R uses operators ==, !=, >, <, >= and <= for logical comparisons
Operator Explanation Example
== x EQUAL y? x == y
!= x NOT EQUAL y? x != y
< x LESS THAN y? x < y
<= x LESS THAN OR EQUAL y? x <= y
> x GREATER THAN y? x > y
>= x GREATER THAN OR EQUAL y? x >= y
x <- 15
y <- 3
z <- x > y
z

x <- -3.5
y <- 4
z <- x > y
z

x <- 'A'
y <- 'a'
z <- x > y
z


x <- 'A'
y <- 'Z'
z <- x > y
z


x <- 'z'
y <- 'A'
z <- x > y
z


x <- 'apple'
y <- 'grape'
z <- x > y
z


x <- 'grape'
y <- 'banana'
z <- x > y
z


x <- TRUE
y <- FALSE
z <- x > y
z


x <- T
y <- F
z <- x > y
z

14.3 Examples: more comparisons

  • R uses operators ==, >, <, >= and <= for comparisons

  • R also uses operators ! (NOT), & (AND) and | (OR)

Operator Meaning X Y Decision Example
& AND TRUE TRUE TRUE X & Y
& AND TRUE FALSE FALSE X & Y
& AND FALSE TRUE FALSE X & Y
& AND FALSE FALSE FALSE X & Y
| OR TRUE TRUE TRUE X | Y
| OR TRUE FALSE TRUE X | Y
| OR FALSE TRUE TRUE X | Y
| OR FALSE FALSE FALSE X | Y
x <- 10L
y <- 5L

z1 <- x + y
z2 <- x - y
z3 <- x

x; y
z1; z2; z3

m <- (x > z1) & (x > z2)
m

n <- (x == z1) & (x < z2)
n

p <- (y > z1) & (y > z2)
p

q <- (y >= z1) & (y <= z2)
q

r <- (y >= z1) | (y <= z2)
r

s <- (x >= z1) | (y >= z3)
s


t <- !(x >= z2) | (y >= z3)
t