# List in R: How to Create R Lists, Select Elements with Example

## What is R List?

R List is an object in R programming which includes matrices, vectors, data frames, or lists within it. R List is also used to store a collection of objects and use them when we need them. We can imagine the R list as a bag to put many different items. When we need to use an item, we can open the bag and use it.

## How to Create a List in R

Below is a step by step process on how to create a list in R:

We can use list() function to create lists in R programming.

list(element_1, …)
arguments:
-element_1: store any type of R object
-…: pass as many objects as specifying. each object needs to be separated by a comma
In the example below, we create three different objects, a vector, a matrix and a data frame using list function in R.

Step 1) Create a Vector

# Vector with numeric from 1 up to 5

vect <- 1:5
Step 2) Create a Matrices

# A 2x 5 matrix

mat <- matrix(1:9, ncol = 5)
dim(mat)
Output:

## [1] 2 5

Step 3) Create Data Frame

# select the 10th row of the built-in R data set EuStockMarkets

df <- EuStockMarkets[1:10,]
Step 4) Create a List in R

Now, we can put the three object into a list R.

# Construct list with these vec, mat, and df:

my_list <- list(vect, mat, df)
my_list
Output:

## [10,] 1645.89 1716.3 1754.3 2497.4

Select Elements from List R
After we built our list, we can access it quite easily. We need to use the [[index]] to select an element in a list. The value inside the double square bracket represents the position of the item in a list we want to extract. For instance, we pass 2 inside the parenthesis, R returns the second element listed.

Now in this R tutorial, let’s try to select the second items of lists in R named my_list, we use my_list[[2]]

# Print second element of the list

my_list[[2]]
Output:

## [2,] 2 4 6 8 1

Built-in Data Frame
Before to create our own data frame, we can have a look at the R data set available online. The prison dataset is a 714x5 dimension. We can get a quick look at the bottom of the data frame with tail() function. By analogy, head() displays the top of the data frame. You can specify the number of rows shown with head (df, 5). We will learn more about the function read.csv() in future tutorial.

PATH <-‘https://raw.githubusercontent.com/guru99-edu/R-Programming/master/prison.csv
Output:

## 5 5 1 84 0 0.2548

We can check the structure of the data frame with str:

# Structure of the data

str(df)
Output:

## \$ black : num 0.256 0.256 0.255 0.255 0.255 …

All variables are stored in the numerical format.