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.
# Vector of stringsmy_list1 <- list("pear", "cherry", "lemon")# vector of numbersmy_list2 <- c(1, 2, 3, 4, 5)# Printing the vectorsmy_list1my_list2
Line 2: We create a list my_list1
containing string values or items.
Line 5: We create another list my_list2
containing numerical values or items.
Lines 8-9: We print the two lists we created.
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.
# 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]
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 []
.