To create a list in R, you can use the “list()” function. The “list()” function accepts single or multiple arguments and returns the list.
lt <- list("SBF", "Alameda") print(lt)
[]  "SBF" []  "Alameda"
You can see that we created a list with two elements. To print the data in the console, use the print() function.
A list is an R object consisting of an ordered collection of objects. The list is a one-dimensional, heterogeneous data structure.
A list is a robust data structure that contains other objects for data analysis with a wide range of functions for manipulating and extracting data.
A list can contain strings, numbers, vectors, and logical values. A list can also have a matrix or a function as its elements,
After creating a list, you can add, update or remove elements per your requirements.
Creating a list with different data types
A list can contain multiple data types like boolean, string, integer, float, function, or matrix.
lt <- list("SBF", TRUE, 19, 21.19, c(19, 21)) print(lt)
[]  "SBF" []  TRUE []  19 []  21.19 []  19 21
We created a list filled with multiple data type elements.
Manipulating list in R
You can manipulate a list by adding, removing, or sorting it.
Adding an element to the list
To add an element to the list, you can use the “append()” function.
rv <- c(11, 46) lt <- list("SBF", TRUE, 19, 21.19) appended_list <- append(lt, rv) print(appended_list)
[]  "SBF" []  TRUE []  19 []  21.19 []  11 []  46
The append() function adds an element at the end of the list. You can see that we added multiple elements to the list.
Removing an element from the list
To remove an element from a list in R, you can use “negative indexing”. The negative index is a way to tell a compiler, “Don’t include this element”.
rv <- c(11, 46) lt <- list("SBF", TRUE, 19, 21.19) print(lt[-2])
[]  "SBF" []  19 []  21.19
The initial list contains four elements, but after removing a second element, our final list has three.
We pass the negative index to the list like lt[-2] to remove the second element from a list.
The best approach to creating a list is to use the list() function. After creating an initial list, you can append or remove the elements from a list.
How to append to an empty list
Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language.