Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Programming and Statistics in R

Exercise 2

This sheet is concerned with logical operations and factors.

1. Create a logical vector x as follows:

x <- seq(-3, 3, length = 200) > 0

2. Negate the vector x, and construct a vector that contains the first
three values, and the last value, of x

!x
x[c(1:3, 200)]

3. Compute the truth table for logical AND

c(T,T,F,F) & c(T,F,F,T)

4. Explore arithmetic with logical and numeric

1:3 + c(T,F,T)

5. Compute the intersection of {1, 2, . . . , 10} and {5, 6, . . . , 15}

intersect(1:10, 5:15)

6. Compute which elements of the set {1, 2, . . . , 10} are contained within
the set {1, 3, 5, ..., 15}.

second.set <- seq(from = 1, to = 15, by = 2)


index <- is.element(1:10, second.set)
(1:10)[index]

(Try running the third command without the ()s. Why does this fail?)

7. Set all the even numbers in the vector z = [1, 2, . . . , 30] to be equal to
half their value

z <- 1:30
(z <- ifelse(z %% 2 == 0, z / 2, z))

1
Problems
1. Compute the truth table for logical OR. The R function xor computes
the logical EXCLUSIVE-OR. What is the difference between the two?
The syntax for xor is as follows: if x, y are vectors, then xor(a, b)
performs the exclusive-or operator on a,b.

2. Consider the vector 1:K, where K is a positive integer. Write an R


command that determines which elements in the vector are exactly
divisible by 3.

3. Assign a vector x <- 1:100. Assign a vector y which contains all the
elements of x that are divisible by 3 or 5 but not both.

You might also like