How to access the items of a vector in R
Overview
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.
Code example
# Vector of stringsmy_vector1 <- c("pear", "cherry", "lemon")# vector of numbersmy_vector2 <- c(1, 2, 3, 4, 5)# Printing the vectorsmy_vector1my_vector2
Code explanation
-
Line 2: We create a vector
my_vector1containing 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.
Accessing the items of a vector
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:
Code example
# 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]
Code explanation
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 [].
Accessing multiple items of a vector
We can also access multiple items of a vector by referring to their different index numbers or the position with the c() function.
Code example
# 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)]