Solutions

Create a vector with c()

Q01. Make the first element of this numeric vector ‘6’.

c(6, 4, 5, 2, 3)
## [1] 6 4 5 2 3

Q02. Make the third element of this character vector ‘economics’.

Note that quotes shouldn’t be used with numbers, but should be used with character strings.

c("apple", "banana", "economics")
## [1] "apple"     "banana"    "economics"

Calculations on vectors

Q03. Add these two numeric vectors.

c(6, 3, 2) + c(3, 2, 1) == c(9, 5, 3)
## [1] TRUE TRUE TRUE

Q04. Find the minimum of this vector.

min(c(6, 3, 2)) == 2
## [1] TRUE

Q05. Find the sum of all elements of this vector.

sum(c(6, 3, 2)) == 11
## [1] TRUE

Q06. Multiply a scalar and a vector.

100 * c(6, 3, 2) == c(600, 300, 200)
## [1] TRUE TRUE TRUE

Q07. Divide two vectors.

c(6, 3, 2) / c(2, 3, 1) == c(12, 9, 2)
## [1] FALSE FALSE  TRUE

Length

Q08. Create a vector of length 5. It can be a character vector or a numeric vector.

length(c(1:5)) == 5
## [1] TRUE

Q09. Create a random character vector that draws “heads” or “tails”.

sample(c("heads","tails"), size = 5, replace = TRUE)
## [1] "tails" "tails" "tails" "heads" "tails"

Pipes

us_data <- tibble(
  year      = c(1957, 1977, 1997, 2017),
  gdpPercap = c(14847, 24073, 35767, 60062),
  lifeExp   = c(69.5, 73.4, 76.8, 78.5)
)

Q10. Your turn: apply ‘print’ to us_data using a pipe.

us_data %>% print()
## # A tibble: 4 × 3
##    year gdpPercap lifeExp
##   <dbl>     <dbl>   <dbl>
## 1  1957     14847    69.5
## 2  1977     24073    73.4
## 3  1997     35767    76.8
## 4  2017     60062    78.5