18.2 Chapter 5: Scalers and vectors

  1. Create the vector [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] in three ways: once using c(), once using a:b, and once using seq().
c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
##  [1]  1  2  3  4  5  6  7  8  9 10

1:10
##  [1]  1  2  3  4  5  6  7  8  9 10

seq(from = 1, to = 10, by = 1)
##  [1]  1  2  3  4  5  6  7  8  9 10
  1. Create the vector [2.1, 4.1, 6.1, 8.1] in two ways, once using c() and once using seq()

c(2.1, 6.1, 6.1, 8.1)
## [1] 2.1 6.1 6.1 8.1

seq(from = 2.1, to = 8.1, by = 2)
## [1] 2.1 4.1 6.1 8.1
  1. Create the vector [0, 5, 10, 15] in 3 ways: using c(), seq() with a by argument, and seq() with a length.out argument.
c(0, 5, 10, 15)
## [1]  0  5 10 15

seq(from = 0, to = 15, by = 5)
## [1]  0  5 10 15

seq(from = 0, to = 15, length.out = 4)
## [1]  0  5 10 15
  1. Create the vector [101, 102, 103, 200, 205, 210, 1000, 1100, 1200] using a combination of the c() and seq() functions
c(seq(from = 101, to = 103, by = 3), 
  seq(from = 200, to = 210, by = 5), 
  seq(from = 1000, to = 1200, by = 100))
## [1]  101  200  205  210 1000 1100 1200
  1. A new batch of 100 pirates are boarding your ship and need new swords. You have 10 scimitars, 40 broadswords, and 50 cutlasses that you need to distribute evenly to the 100 pirates as they board. Create a vector of length 100 where there is 1 scimitar, 4 broadswords, and 5 cutlasses in each group of 10. That is, in the first 10 elements there should be exactly 1 scimitar, 4 broadswords and 5 cutlasses. The next 10 elements should also have the same number of each sword (and so on).
swords <- rep(c("scimitar", rep("broadswoard", 4), rep("cutlass", 5)), times = 100)
head(swords)
## [1] "scimitar"    "broadswoard" "broadswoard" "broadswoard" "broadswoard" "cutlass"
  1. Create a vector that repeats the integers from 1 to 5, 10 times. That is [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, …]. The length of the vector should be 50!
rep(1:5, times = 10)
##  [1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
  1. Now, create the same vector as before, but this time repeat 1, 10 times, then 2, 10 times, etc., That is [1, 1, 1, …, 2, 2, 2, …, … 5, 5, 5]. The length of the vector should also be 50
rep(1:5, each = 10)
##  [1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5
  1. Create a vector containing 50 samples from a Normal distribution with a population mean of 20 and standard deviation of 2.
rnorm(n = 50, mean = 20, sd = 2)
##  [1] 18 22 23 17 22 22 17 22 20 21 22 23 24 21 22 23 23 20 21 18 21 23 18 20 17 19 19 20 22 23 20 18 18 21 21 19 22 23 24 20 19 17
## [43] 19 24 16 21 22 18 18 23
  1. Create a vector containing 25 samples from a Uniform distribution with a lower bound of -100 and an upper bound of -50.
runif(n = 25, min = -100, max = -50)
##  [1]  -65 -100  -53  -63  -92  -78  -75  -60  -76  -69  -77  -76  -73  -75  -53  -60  -59  -96  -78  -61  -90  -77  -72  -91  -70