c(1, 2, 3, 4, 5)
mean(num_vec)
Basic Operations: Exercises
Exercise 1
What does the function seq
do?
- Repeats a value multiple times.
- Builds a sequence of values.
- Loads a SQL data base.
- It’s part of another package and therefore not loaded in
Base R
.
Hint
Use the help function ?
.
Solution
- Repeats a value multiple times.
- Builds a sequence of values.
- Loads a SQL data base.
- It’s part of another package and therefore not loaded in R.
Exercise 2
Why does the following code not work? Correct it so it does.
Hint
Does the object num_vec
actually exist?
Solution
The object num_vec
hasn’t been assigned yet. So let’s do that:
<- c(1, 2, 3, 4, 5)
num_vec mean(num_vec)
[1] 3
Exercise 3
Build the following vector with as little code as possible:
<- 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) vec_1
Hint
Use seq()
and rep()
. You can also build consecutive sequences using :
.
Solution
<- c(1:5, seq(from = 5, to = 5.5, by = 0.1), rep(x = 2, times = 8))
vec_1 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)
.
<- c(sqrt(100)^3, exp(-6), 22.02/3 * sqrt(4^2) * 0.25, -120987/(47621 * 1.3 ^ 4 )) vec_num
Hint
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”).
Solution
== 1000 | (vec_num < sqrt(11) & vec_num > log(1.001)) vec_num
[1] TRUE TRUE FALSE FALSE