Skip to Content

How to Create a List in R?

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)

Output:

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4

[[5]]
[1] 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[[3]])

Output:

[1] 3

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)

Output:

[[1]]
[1] 9

[[2]]
[1] "cat"

[[3]]
[1] 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 class() function.

# get type of list elements
print(class(ls[[1]]))
print(class(ls[[2]]))
print(class(ls[[3]]))

Output:

[1] "numeric"
[1] "character"
[1] "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.


Author

  • Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.