<- c(1, 2, 3)) (y1
[1] 1 2 3
<- c(TRUE, FALSE, TRUE, TRUE)) (y2
[1] TRUE FALSE TRUE TRUE
<- c("bob", "suzy", "danny")) (y3
[1] "bob" "suzy" "danny"
There are many different ways to generate vectors in R. Some involve combining explicitly specified elements, while others use algorithmic rules to generate value that follow some pattern. Below, we’ll cover some of the most common ways to generate vectors.
The concatenation function, c()
, constructs a vector by joining its arguments into a single vector.
[1] 1 2 3
[1] TRUE FALSE TRUE TRUE
[1] "bob" "suzy" "danny"
The outer parentheses in these examples are just a handy piece of syntactic sugar. They allow us to assign a value (e.g., c(1, 2, 3
) to an object (e.g., y1
) and print that object in a single command. You don’t need to use these extra parentheses if you don’t want to print the value of object your creating.
The colon operator, :
, creates a sequence of regularly spaced values between two endpoints. Each element in the resulting vector is separated from it’s neighbors by \(\pm\) 1.
This :
operator is primarily intended for creating sequences of whole numbers, but it will also work with decimal-valued arguments, though the results might not be what you’d expect. Notice where the sequence begins and ends in the following example.
Without running the code, see if you can generalize what you know about the :
operator to answer the following questions.
:
using to generate this vector?The resulting vector looks like this:
[1] 1.2 2.2 3.2 4.2 5.2
This vector is generated by assigning 1.2 as the first element and then adding 1 to define the next element. Each subsequent element is defined by adding one to the last element until the resulting value exceeds the upper bound we requested (i.e., 5.3). So, the last element in the vector is 5.2, since that’s the largest value that can be generated in unit steps from 1.2 without exceeding 5.3.
To generate regular sequences with non-unit steps between the elements, we can use seq()
. The seq()
function allows you to specify the step size or the total number of elements in the resulting vector with the by
or length.out
arguments, respectively.
# Create a numeric vector starting at 0, ending at 1, with elements
# increasing by steps of 0.25
seq(from = 0, to = 1, by = 0.25)
[1] 0.00 0.25 0.50 0.75 1.00
[1] 0.00 0.25 0.50 0.75 1.00
# Create a numeric vector of 10 evenly spaced values starting at -1 and
# ending at 1
seq(-1, 1, length.out = 10)
[1] -1.0000000 -0.7777778 -0.5555556 -0.3333333 -0.1111111 0.1111111
[7] 0.3333333 0.5555556 0.7777778 1.0000000
The rep()
function creates vectors by repeating it’s first argument as many times as requested.
Use the each
argument to repeat each element of the first argument each
number of times.
Create a numeric vector containing the five even integers from 4 to 12 (inclusive).