R – Lists

Last Updated : 11 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A list in R programming is a generic object consisting of an ordered collection of objects. Lists are one-dimensional, heterogeneous data structures.

The list can be a list of vectors, a list of matrices, a list of characters, a list of functions, and so on. 

A list is a vector but with heterogeneous data elements. A list in R is created with the use of the list() function.

R allows accessing elements of an R list with the use of the index value. In R, the indexing of a list starts with 1 instead of 0.

Creating a List

To create a List in R you need to use the function called “list()“.

In other words, a list is a generic vector containing other objects. To illustrate how a list looks, we take an example here. We want to build a list of employees with the details. So for this, we want attributes such as ID, employee name, and the number of employees. 

Example:  

R




# R program to create a List
  
# The first attributes is a numeric vector
# containing the employee IDs which is created
# using the command here
empId = c(1, 2, 3, 4)
  
# The second attribute is the employee name
# which is created using this line of code here
# which is the character vector
empName = c("Debi", "Sandeep", "Subham", "Shiba")
  
# The third attribute is the number of employees
# which is a single numeric variable.
numberOfEmp = 4
  
# We can combine all these three different
# data types into a list
# containing the details of employees
# which can be done using a list command
empList = list(empId, empName, numberOfEmp)
  
print(empList)


Output

[[1]]
[1] 1 2 3 4

[[2]]
[1] "Debi"    "Sandeep" "Subham"  "Shiba"  

[[3]]
[1] 4



Naming List Components

Naming list components make it easier to access them.

Example:

R




# Creating a named list
my_named_list <- list(name = "Sudheer", age = 25, city = "Delhi")
 
# Printing the named list
print(my_named_list)


Output

$name
[1] "Sudheer"

$age
[1] 25

$city
[1] "Delhi"



Accessing R List Components

We can access components of an R list in two ways. 

1. Access components by names:

All the components of a list can be named and we can use those names to access the components of the R list using the dollar command.

Example: 

R




# R program to access
# components of a list
 
# Creating a list by naming all its components
empId = c(1, 2, 3, 4)
empName = c("Debi", "Sandeep", "Subham", "Shiba")
numberOfEmp = 4
empList = list(
  "ID" = empId,
  "Names" = empName,
  "Total Staff" = numberOfEmp
  )
print(empList)
 
# Accessing components by names
cat("Accessing name components using $ command\n")
print(empList$Names)


Output

$ID
[1] 1 2 3 4

$Names
[1] "Debi"    "Sandeep" "Subham"  "Shiba"  

$`Total Staff`
[1] 4

Accessing name components using $ command
[1] "Debi"    "Sandeep" "Subham"  "Shiba"  


2. Access components by indices:

We can also access the components of the R list using indices.

To access the top-level components of a R list we have to use a double slicing operator “[[ ]]” which is two square brackets and if we want to access the lower or inner-level components of a R list we have to use another square bracket “[ ]” along with the double slicing operator “[[ ]]“.

Example: 

R




# R program to access
# components of a list
 
# Creating a list by naming all its components
empId = c(1, 2, 3, 4)
empName = c("Debi", "Sandeep", "Subham", "Shiba")
numberOfEmp = 4
empList = list(
  "ID" = empId,
  "Names" = empName,
  "Total Staff" = numberOfEmp
  )
print(empList)
 
# Accessing a top level components by indices
cat("Accessing name components using indices\n")
print(empList[[2]])
 
# Accessing a inner level components by indices
cat("Accessing Sandeep from name using indices\n")
print(empList[[2]][2])
 
# Accessing another inner level components by indices
cat("Accessing 4 from ID using indices\n")
print(empList[[1]][4])


Output

$ID
[1] 1 2 3 4

$Names
[1] "Debi"    "Sandeep" "Subham"  "Shiba"  

$`Total Staff`
[1] 4

Accessing name components using indices
[1] "Debi"    "Sandeep" "Subham"  "Shiba"  
Accessing Sandeep from na...

Modifying Components of a List

A R list can also be modified by accessing the components and replacing them with the ones which you want.

Example: 

R




# R program to edit
# components of a list
 
# Creating a list by naming all its components
empId = c(1, 2, 3, 4)
empName = c("Debi", "Sandeep", "Subham", "Shiba")
numberOfEmp = 4
empList = list(
  "ID" = empId,
  "Names" = empName,
  "Total Staff" = numberOfEmp
)
cat("Before modifying the list\n")
print(empList)
 
# Modifying the top-level component
empList$`Total Staff` = 5
 
# Modifying inner level component
empList[[1]][5] = 5
empList[[2]][5] = "Kamala"
 
cat("After modified the list\n")
print(empList)


Output

Before modifying the list
$ID
[1] 1 2 3 4

$Names
[1] "Debi"    "Sandeep" "Subham"  "Shiba"  

$`Total Staff`
[1] 4

After modified the list
$ID
[1] 1 2 3 4 5

$Names
[1] "Debi"    "Sandeep" "Subham" ...

Concatenation of lists

Two R lists can be concatenated using the concatenation function. So, when we want to concatenate two lists we have to use the concatenation operator.

Syntax:  

list = c(list, list1)
list = the original list 
list1 = the new list 

Example: 

R




# R program to edit
# components of a list
 
# Creating a list by naming all its components
empId = c(1, 2, 3, 4)
empName = c("Debi", "Sandeep", "Subham", "Shiba")
numberOfEmp = 4
empList = list(
  "ID" = empId,
  "Names" = empName,
  "Total Staff" = numberOfEmp
)
cat("Before concatenation of the new list\n")
print(empList)
 
# Creating another list
empAge = c(34, 23, 18, 45)
 
# Concatenation of list using concatenation operator
empList = c(empName, empAge)
 
cat("After concatenation of the new list\n")
print(empList)


Output

Before concatenation of the new list
$ID
[1] 1 2 3 4

$Names
[1] "Debi"    "Sandeep" "Subham"  "Shiba"  

$`Total Staff`
[1] 4

After concatenation of the new list
[1] "Debi"    "Sandeep" "Subham"  "S...

Adding Item to List

To add an item to the end of list, we can use append() function.

R




# creating a list
my_numbers = c(1,5,6,3)
#adding number at the end of list
append(my_numbers, 45)
#printing list
my_numbers


Output

[1]  1  5  6  3 45
[1] 1 5 6 3


Deleting Components of a List

To delete components of a R list, first of all, we need to access those components and then insert a negative sign before those components. It indicates that we had to delete that component. 

Example: 

R




# R program to access
# components of a list
 
# Creating a list by naming all its components
empId = c(1, 2, 3, 4)
empName = c("Debi", "Sandeep", "Subham", "Shiba")
numberOfEmp = 4
empList = list(
  "ID" = empId,
  "Names" = empName,
  "Total Staff" = numberOfEmp
)
cat("Before deletion the list is\n")
print(empList)
 
# Deleting a top level components
cat("After Deleting Total staff components\n")
print(empList[-3])
 
# Deleting a inner level components
cat("After Deleting sandeep from name\n")
print(empList[[2]][-2])


Output

Before deletion the list is
$ID
[1] 1 2 3 4

$Names
[1] "Debi"    "Sandeep" "Subham"  "Shiba"  

$`Total Staff`
[1] 4

After Deleting Total staff components
$ID
[1] 1 2 3 4

$Names
[1] "Debi"    "Sand...

Merging list

We can merge the R list by placing all the lists into a single list.

R




# Create two lists.
lst1 <- list(1,2,3)
lst2 <- list("Sun","Mon","Tue")
 
# Merge the two lists.
new_list <- c(lst1,lst2)
 
# Print the merged list.
print(new_list)


Output:

[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
[[4]]
[1] "Sun"
[[5]]
[1] "Mon"
[[6]]
[1] "Tue"

Converting List to Vector

Here we are going to convert the R list to vector, for this we will create a list first and then unlist the list into the vector.

R




# Create lists.
lst <- list(1:5)
print(lst)
 
# Convert the lists to vectors.
vec <- unlist(lst)
 
print(vec)


Output

[[1]]
[1] 1 2 3 4 5

[1] 1 2 3 4 5


R List to matrix

We will create matrices using matrix() function in R programming. Another function that will be used is unlist() function to convert the lists into a vector.

R




# Defining list
lst1 <- list(list(1, 2, 3),
            list(4, 5, 6))
 
# Print list
cat("The list is:\n")
print(lst1)
cat("Class:", class(lst1), "\n")
 
# Convert list to matrix
mat <- matrix(unlist(lst1), nrow = 2, byrow = TRUE)
 
# Print matrix
cat("\nAfter conversion to matrix:\n")
print(mat)
cat("Class:", class(mat), "\n")


Output

The list is:
[[1]]
[[1]][[1]]
[1] 1

[[1]][[2]]
[1] 2

[[1]][[3]]
[1] 3


[[2]]
[[2]][[1]]
[1] 4

[[2]][[2]]
[1] 5

[[2]][[3]]
[1] 6


Class: list 

After conversion to matrix:
     [,1] [,2] [,3]
[1,...

In this article we have covered Lists in R, we have covered list operations like creating, naming, merging and deleting a list in R language. R list is an important concept and should not be skipped.

Hope you learnt about R lists and it’s operations in this article.

Also Check:



Previous Article
Next Article

Similar Reads

Create Matrix and Data Frame from Lists in R Programming
In R programming, there 5 basic objects. Lists are the objects that can contain heterogeneous types of elements, unlike vectors. Matrices can contain the same type of elements or homogeneous elements. On the other hand, data frames are similar to matrices but have an advantage over matrices to keep heterogeneous elements. In this article, we'll lea
3 min read
Performing Operations on Multiple Lists simultaneously in R Programming - mapply() Function
mapply() function in R Language is stand for multivariate apply and is used to perform mathematical operations on multiple lists simultaneously. Syntax: mapply(func, list1, list2, ...) Parameters: list1, list2, ...: Created Listsfunc: operation to be appliedmapply() Function in R Language ExampleExample 1: Sum of two lists using mapply() function i
1 min read
Operations on Lists in R Programming
Lists in R language, are the objects which comprise elements of diverse types like numbers, strings, logical values, vectors, list within a list and also matrix and function as its element. A list is generated using list() function. It is basically a generic vector that contains different objects. R allows its users to perform various operations on
4 min read
Shift a column of lists in data.table by group in R
In this article, we will discuss how to shift a column of lists in data.table by a group in R Programming Language. The data table subsetting can be performed and the new column can be created and its values are assigned using the shift method in R. The type can be specified as either "lead" or "lag" depending upon the direction in which the elemen
2 min read
Unnesting a list of lists in a data frame column in R
Working with data that has lists within columns is frequent when using R programming language. These lists may include various kinds of information, including other lists. But, working with these hierarchical lists can be difficult, especially if we wish to analyze or visualize the data. A list of lists in a data frame column can be de-nested to as
6 min read
Function to transform lists of different lengths into data frame utilizing recycling in R
In R Programming Language recycling is a feature that automatically extends shorter vectors or lists to match the length of longer vectors when performing operations. This can be particularly useful when you want to transform lists of different lengths into a data frame. Here’s how you can achieve this: Understanding Recycling in RRecycling in R re
3 min read
How to Find and Count Missing Values in R DataFrame
In this article, we will be discussing how to find and count missing values in the R programming language. Find and Count Missing Values in the R DataFrameGenerally, missing values in the given data are represented with NA. In R programming, the missing values can be determined by is.na() method. This method accepts the data variable as a parameter
4 min read
A Guide to dnorm, pnorm, rnorm, and qnorm in R
In this article, we will be looking at a guide to the dnorm, pnorm, qnorm, and rnorm methods of the normal distribution in the R programming language. dnorm function This function returns the value of the probability density function (pdf) of the normal distribution given a certain random variable x, a population mean μ, and the population standard
3 min read
How to Find Confidence Intervals in R?
The confidence interval in R signifies how much uncertainty is present in statistical data. a fundamental statistical technique, confidence intervals offer a range of likely values for an unknown population parameter based on sample data. They are essential to decision-making, hypothesis testing, and statistical inference.In other words, it is defi
6 min read
apply(), lapply(), sapply(), and tapply() in R
In this article, we will learn about the apply(), lapply(), sapply(), and tapply() functions in the R Programming Language. The apply() collection is a part of R essential package. This family of functions helps us to apply a certain function to a certain data frame, list, or vector and return the result as a list or vector depending on the functio
4 min read
How to Create Tables in R?
In this article, we will discuss how to create tables in R Programming Language. Method 1: Create a table from scratch We can create a table by using as.table() function, first we create a table using matrix and then assign it to this method to get the table format. Syntax: as.table(data) Example: In this example, we will create a matrix and assign
2 min read
Change column name of a given DataFrame in R
A data frame is a tabular structure with fixed dimensions, of each rows as well as columns. It is a two-dimensional array like object with numerical, character based or factor-type data. Each element belonging to the data frame is indexed by a unique combination of the row and column number respectively. Column names are addressed by unique names.
5 min read
R Tutorial | Learn R Programming Language
R Tutorial is designed for beginners and experts. This free R Tutorial gives you concepts of the R programming language. Here you will get a detailed introduction, features, installation, variables, data types, operators, if statements, vectors, data handling, graphics, and statistical modeling of R programming. What is R Programming?R is an interp
7 min read
R - Data Frames
R Programming Language is an open-source programming language that is widely used as a statistical software and data analysis tool. Data Frames in R Language are generic data objects of R that are used to store tabular data.  Data frames can also be interpreted as matrices where each column of a matrix can be of different data types. R DataFrame is
10 min read
Taking Input from User in R Programming
Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. Like other programming languages in R it's also possible to take input from the user. For doing so, there are two methods in R. Using readline() me
7 min read
Printing Output of an R Program
In R there are various methods to print the output. Most common method to print output in R program, there is a function called print() is used. Also if the program of R is written over the console line by line then the output is printed normally, no need to use any function for print that output. To do this just select the output variable and pres
4 min read
Read contents of a CSV File in R Programming - read.csv() Function
read.csv() function in R Language is used to read "comma separated value" files. It imports data in the form of a data frame. Syntax: read.csv(file, header, sep, dec) Parameters: file: the path to the file containing the data to be imported into R. header: logical value. If TRUE, read.csv() assumes that your file has a header row, so row 1 is the n
3 min read
Control Statements in R Programming
Control statements are expressions used to control the execution and flow of the program based on the conditions provided in the statements. These structures are used to make a decision after assessing the variable. In this article, we'll discuss all the control statements with the examples. In R programming, there are 8 types of control statements
4 min read
R - Matrices
R-matrix is a two-dimensional arrangement of data in rows and columns. In a matrix, rows are the ones that run horizontally and columns are the ones that run vertically. In R programming, matrices are two-dimensional, homogeneous data structures. These are some examples of matrices: Creating a Matrix in RTo create a matrix in R you need to use the
12 min read
R - Lists
A list in R programming is a generic object consisting of an ordered collection of objects. Lists are one-dimensional, heterogeneous data structures. The list can be a list of vectors, a list of matrices, a list of characters, a list of functions, and so on. A list is a vector but with heterogeneous data elements. A list in R is created with the us
8 min read
R Data Types
Different forms of data that can be saved and manipulated are defined and categorized using data types in computer languages, including R. Each R data type has unique properties and associated operations. What are R Data types?R Data types are used to specify the kind of data that can be stored in a variable. For effective memory consumption and pr
8 min read
Functions in R Programming
A function accepts input arguments and produces the output by executing valid R commands that are inside the function. Functions are useful when you want to perform a certain task multiple times. In R Programming Language when you are creating a function the function name and the file in which you are creating the function need not be the same and
8 min read
Getting started with Data Visualization in R
Data visualization is the technique used to deliver insights in data using visual cues such as graphs, charts, maps, and many others. This is useful as it helps in intuitive and easy understanding of the large quantities of data and thereby make better decisions regarding it. Data Visualization in R Programming LanguageThe popular data visualizatio
6 min read
Data Structures in R Programming
A data structure is a particular way of organizing data in a computer so that it can be used effectively. The idea is to reduce the space and time complexities of different tasks. Data structures in R programming are tools for holding multiple values. R’s base data structures are often organized by their dimensionality (1D, 2D, or nD) and whether t
6 min read
R Vectors
R Vectors are the same as the arrays in R language which are used to hold multiple data values of the same type. One major key point is that in R Programming Language the indexing of the vector will start from '1' and not from '0'. We can create numeric vectors and character vectors as well.  Creating a vectorA vector is a basic data structure that
5 min read
R Operators
Operators are the symbols directing the compiler to perform various kinds of operations between the operands. Operators simulate the various mathematical, logical, and decision operations performed on a set of Complex Numbers, Integers, and Numericals as input operands. R Operators R supports majorly four kinds of binary operators between a set of
9 min read
R Programming Language - Introduction
The R Language stands out as a powerful tool in the modern era of statistical computing and data analysis. Widely embraced by statisticians, data scientists, and researchers, the R Language offers an extensive suite of packages and libraries tailored for data manipulation, statistical modeling, and visualization. In this article, we explore the fea
7 min read
Histograms in R language
A histogram contains a rectangular area to display the statistical information which is proportional to the frequency of a variable and its width in successive numerical intervals. A graphical representation that manages a group of data points into different specified ranges. It has a special feature that shows no gaps between the bars and is simil
3 min read
R - Bar Charts
Bar charts are a popular and effective way to visually represent categorical data in a structured manner. R stands out as a powerful programming language for data analysis and visualization. In this article, we'll look at how to make visually appealing bar charts in R. Bar Charts using RA bar chart also known as bar graph is a pictorial representat
5 min read
Simple Linear Regression in R
Regression shows a line or curve that passes through all the data points on the target-predictor graph in such a way that the vertical distance between the data points and the regression line is minimum What is Linear Regression?Linear Regression is a commonly used type of predictive analysis. Linear Regression is a statistical approach for modelli
12 min read
Article Tags :
three90RightbarBannerImg