In this tutorial, we will look at the list data structure in the R programming language and how to create a list with the help of some examples.
What are lists in R?
A list is a built-in data structure in R that helps you store one-dimensional data. Unlike vectors which store data only of the same type, a list in R can store data of different types. Thus, lists are commonly used to create a sequence of values that may not necessarily have the same type.
How to create a list in R?
You can use the built-in
list() function in R to create a list. Pass the elements that you want the list to have as arguments to the
list() function. The following is the syntax –
# create a list ls <- list(item1, item2, item3, ...)
Let’s look at some examples of creating a list in R.
List of numbers in R
First, let’s create a list of numbers, for example, 1, 2, 3, 4, and 5. For this, use the
list() function and pass the list elements as arguments.
# create a list ls <- list(1, 2, 3, 4, 5) # display the list print(ls)
[]  1 []  2 []  3 []  4 []  5
We get a list of numbers. Note that elements in a list are indexed starting from 1 and you can use this index to access a particular element in a list using the
[] notation. For example, let’s get the element at index 3 in the above list.
# access list element by index print(ls[])
We get the element at index 3, which is 3 in the above list.
List with elements of different types in R
Let’s look at another example, this time we will create a list of elements with different data types.
# create a list ls <- list(9, "cat", TRUE) # display the list print(ls)
[]  9 []  "cat" []  TRUE
Here, our list contains a numeric value, a character value, and a logical value. You can check the data type for a list element using the
# get type of list elements print(class(ls[])) print(class(ls[])) print(class(ls[]))
 "numeric"  "character"  "logical"
You can see that we get the type for all the three elements in the list.
You might also be interested in –
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.