c(1, 2, 3, 4, 5)
mean(num_vec)Basic Operations: Exercises
Exercise 1
What does the function seq do?
TipHint
Use the help function ?.
CautionSolution
Exercise 2
Why does the following code not work? Correct it so it does.
TipHint
Does the object num_vec actually exist?
CautionSolution
The object num_vec hasn’t been assigned yet. So let’s do that:
num_vec <- c(1, 2, 3, 4, 5)
mean(num_vec)[1] 3
Exercise 3
Build the following vector with as little code as possible:
vec_1 <- c(
1.0,
2.0,
3.0,
4.0,
5.0,
5.1,
5.2,
5.3,
5.4,
5.5,
2.0,
2.0,
2.0,
2.0,
2.0,
2.0,
2.0,
2.0
)
TipHint
Use seq() and rep(). You can also build consecutive sequences using :.
CautionSolution
vec_1 <- c(1:5, seq(from = 5, to = 5.5, by = 0.1), rep(x = 2, times = 8))
vec_1 [1] 1.0 2.0 3.0 4.0 5.0 5.0 5.1 5.2 5.3 5.4 5.5 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0
Exercise 4
Find all of the elements in the vector vec_num that are either equal to 1000, or lie between sqrt(11) and log(1.001).
vec_num <- c(
sqrt(100)^3,
exp(-6),
22.02 / 3 * sqrt(4^2) * 0.25,
-120987 / (47621 * 1.3^4)
)
TipHint
You need to combine three logical statements. Go at it step by step: first find all elements in vec_num that are equal to 1000, and then add a comparison for the rest of the statement behind an | (“or”).
CautionSolution
vec_num == 1000 | (vec_num < sqrt(11) & vec_num > log(1.001))[1] TRUE TRUE FALSE FALSE