How to access the items of a list in R
Overview
A list in R is simply a collection of ordered or changeable data.
The list items are combined together using the list() function. This function takes the items we want in our list as its parameter.
Now, let’s create a list.
Code example
# Vector of stringsmy_list1 <- list("pear", "cherry", "lemon")# vector of numbersmy_list2 <- c(1, 2, 3, 4, 5)# Printing the vectorsmy_list1my_list2
Code explanation
-
Line 2: We create a list
my_list1containing string values or items. -
Line 5: We create another list
my_list2containing numerical values or items. -
Lines 8-9: We print the two lists we created.
How to access the items of a list
To access the items of a list, we simply refer to its index number inside brackets []. In R, the first list item has its index as 1, the second item has its index as 2, and so on.
In the code below, we want to access the items of a list.
Code example
# creating a listmy_list <- list("pear", "cherry", "lemon")# accessing the first item of the listmy_list[1]# accessing the second item of the listmy_list[2]
Code explanation
We can see that we were able to access the items of the vector my_vector by simply referring to the index number of the specific item inside brackets [].