#
# CHAPTER 13: Relational operators
#
# > >= < <= == !=
#
x = c(2, -3, 0, 8) # a vector of numeric elements
x # display x
x == 7 # which elements in x, if any, equal 7?
x == 8 # which elements in x equal 8?
sqrt(3) * sqrt(3) # the square root of 3 squared is 3
sqrt(3) * sqrt(3) == 3 # test for equality
all.equal(sqrt(3) * sqrt(3), 3)
x != 0 # which elements in x are nonzero?
x < 0 # which elements in x are negative?
c(x == 0, x != 0) # vector of eight logical elements
x[x < 0] = 17 # set all negative elements in x to 17
x # display x
"C" < "R" # is "C" less than "R"
y = c(1, 4, 2, 5) # another vector of numeric elements
y # display y
x > y # which elements of x are greater than y
x[x > y] # elements of x in which x is greater than y
x[x > y] = x[x > y] * 4 # multiply elements of x such that x > y by four
x # display x
which(x < 5) # indexes of elements in x that are less than 5
which(x < mean(x)) # indexes of elements in x that are less than xbar
name = c("Joe", "Ian", "Liz", "Ali") # vector of names
age = c(19, 21, 18, 20) # vector of ages
va = c(TRUE, FALSE, TRUE, FALSE) # vector of virginia resident statuses
name[age < 21 & va] # names of young virginians
x = c(2, -7, 0, 9, 3.3) # a vector of five numeric elements
ifelse(x >= 0, "nonnegative", "negative")
x = c(2, -7, 0, 9, 3.3) # a vector of five numeric elements
ifelse(abs(x) > 5, "largemag", "smallmag")
x = c(2, -7, 0, 9, 3.3) # a vector of five numeric elements
ifelse(x < -5, -5, ifelse(x > 5, 5, x))
x = c(2, -7, 0, 9, 3.3) # a vector of five numeric elements
pmax(pmin(x, 5), -5) # left truncate at -5 and right truncate at 5
x = -1:2 # x is a vector with elements -1, 0, 1, 2
sqrt(-1:2) # the square roots of -1, 0, 1, 2
sqrt(ifelse(x >= 0, x, NaN))
exists("my.sign") # does the object named my.sign exist?
my.sign = function(x) ifelse(x > 0, 1, ifelse(x == 0, 0, -1))
x = -1:2 # x is a vector with elements -1, 0, 1, 2
x # display x
my.sign(x) # apply the my.sign function to x
y = matrix(-2:3, 2, 3) # y is a 2 x 3 matrix with integer elements
y # display y
my.sign(y) # apply the my.sign function to y