A vector in R is simply a list of data type items.
The items of a vector are combined using the c()
function. The c()
function takes the lists of items we want in our vector object as its parameter.
Let’s create a vector.
# Vector of stringsmy_vector1 <- c("pear", "cherry", "lemon")# vector of numbersmy_vector2 <- c(1, 2, 3, 4, 5)# Printing the vectorsmy_vector1my_vector2
Line 2: We create a vector my_vector1
containing string values or items.
Line 5: We create another vector, my_vector2
, containing numerical values or items.
Lines 8 & 9: We print the two vectors we create.
To access the items of a vector, we refer to its index number inside the brackets []
. In R, the first item of a vector has its index as 1
, the second has its index as 2
, and so on.
In the code below, we want to access the items of a vector:
# creating a vectormy_vector <- c("pear", "cherry", "lemon")# accessing the first item of the vector objectmy_vector[1]# accessing the second item of the vector objectmy_vector[2]
We can see that we could access the vector my_vector
items by simply referring to the index number of the specific item inside brackets [].
We can also access multiple items of a vector by referring to their different index numbers or the position with the c()
function.
# creating a vectormy_vector <- c("pear", "cherry", "lemon")# accessing the first and third items of the vector using the c() functonmy_vector[c(1, 3)]