Chapter 34 Vectors with Repeating Elements

Welcome back to Quantitative Reasoning! In tutorial 2, we learned how to create vectors from individual elements with the c() function. If the elements follow special patterns, R often has shortcuts so that we don’t need to insert all elements by hand. We saw in tutorial 6 that we can get a sequence of integers with the colon operator. For example, 1:5 returns a sequence of integers between 1 and 5.

1:5
## [1] 1 2 3 4 5

For more general sequences, we learned that we can use the seq() function. For instance, seq(0, 1, 0.2) returns a sequence of numbers from 0 to 1 with increments of 0.2.

seq(0, 1, 0.2)
## [1] 0.0 0.2 0.4 0.6 0.8 1.0

In this short tutorial, we learn shortcut functions for another important special case: vectors with repeating elements. A typical use case for a vector with repeating elements is a simulation of a random experiment. Different elements in the vector may count different kinds of random events that occur during the simulation. In this case, we want to initially set all elements equal to zero to indicate that no event of any kind has occurred until now.

In R, there are two different options for generating a vector with a specified number of zeros. The first option is the function numeric(). The second option is the function rep(). If we use numeric(), then we pass an integer argument that specifies the number of zeros. For example, numeric(5) returns a vector with five zeros.

numeric(5)
## [1] 0 0 0 0 0

If we use rep() instead of numeric(), we must pass two arguments: the element we want to repeat and the number of repetitions. The equivalent of numeric(5) is rep(0, 5).

rep(0, 5)
## [1] 0 0 0 0 0

The rep() function is more general than numeric() because rep() can repeat elements that are not zero, for example the character string "diamonds".

rep("diamonds", 5)
## [1] "diamonds" "diamonds" "diamonds" "diamonds" "diamonds"

rep() can also repeat patterns that consist of more than a single value. For example, here is how we repeat the four suits in a regular deck of playing cards five times.

rep(c("diamonds", "clubs", "spades", "hearts"), 5)
##  [1] "diamonds" "clubs"    "spades"   "hearts"   "diamonds" "clubs"   
##  [7] "spades"   "hearts"   "diamonds" "clubs"    "spades"   "hearts"  
## [13] "diamonds" "clubs"    "spades"   "hearts"   "diamonds" "clubs"   
## [19] "spades"   "hearts"

We use this method in our next tutorial to simulate random draws from a deck of cards.

In summary, we learned that we can use numeric(n) to generate a vector with n zeros. We can create a vector that contains n repetitions of a vector v with rep(v, n). Next time we apply this knowledge when we write our first for-loops.

See you soon.