How to Create a List in R

R list is one of the most versatile data types thanks to its ability to adapt heterogeneous elements. R does not have a built-in array data type, but it has a list.

What is a list?

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.

Create a list in R

To create a list in R, use the list() function. The list() function accepts single or multiple arguments and returns the list.

lt <- list("SBF", "Alameda")

print(lt)

Output

[[1]]
[1] "SBF"

[[2]]
[1] "Alameda"

You can see that we created a list with two elements. To print the data in the console, use the print() function.

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)

Output

[[1]]
[1] "SBF"

[[2]]
[1] TRUE

[[3]]
[1] 19

[[4]]
[1] 21.19

[[5]]
[1] 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, use the append() function.

rv <- c(11, 46)
lt <- list("SBF", TRUE, 19, 21.19)

appended_list <- append(lt, rv)

print(appended_list)

Output

[[1]]
[1] "SBF"

[[2]]
[1] TRUE

[[3]]
[1] 19

[[4]]
[1] 21.19

[[5]]
[1] 11

[[6]]
[1] 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, 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])

Output

[[1]]
[1] "SBF"

[[2]]
[1] 19

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

Conclusion

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.

Further reading

How to create an empty list

How to append to an empty list

as.list() in R

Leave a Comment