How to Create Empty List in R Programming

A list is a particular type of vector but can store mixed data types. In this example, we wanted to create a list with no elements and has a length of 0. To initialize the empty vector of a given length, you can use the rep() function.

your_length <- 10
empty_vec <- rep(NA, your_length)
empty_vec

Output

[1] NA NA NA NA NA NA NA NA NA NA

That is it. We have created an empty vector using the rep() function. The rep() is an inbuilt generic R function that replicates the values in the provided vector

A list is actually a kind of vector. I would say that to call a vector (a series of items of the same data type), is more specifically to call an atomic vector. A list, on the other side, is just a vector that can contain more than one type of data. 

So, to empty the list, you can use the vector() function but let’s see it in-depth in the following section.

Create Empty List in R

To create an empty list in R, use the vector() function. The vector() function takes two arguments: mode and length. The mode is, in our case, is a list, and length is the number of elements in the list, and the list ends up actually empty, filled with NULL.

len <- 5
empty_list <- vector(mode = "list", length = len)
empty_list
class(empty_list)

Output

[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL

[[5]]
NULL

[1] "list"

From the output, you can see that we get the empty list filled with NULL values. We passed 5 as the length of the list elements as a parameter, and the vector() function returns an empty list with five NULL values.

There are no restrictions on the data type or structure of the individual list elements.

Empty an existing list in R

To empty an existing list in R, write the list <<- NULL code. The <<- operator assigns global variables in R.

rv <- c(1, 2, 3, 4)

lst <- list(rv)
lst
typeof(lst)
lst <<- NULL
lst
typeof(lst)

Output

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

[1] "list"
NULL
[1] "NULL"

You can set elements to NULL. R language supports several null-able values, and it is relatively important to understand how these values behave when making data pre-processing and data munging. In general, R supports: NULL; NA; NaN; Inf / -Inf; NULL is an object and is returned when an expression or function results in an undefined value.

That is it for creating an empty list in the R programming tutorial.

See also

How to Create an empty Vector

How to Create an empty Data Frame

Leave a Comment