How to Create an Empty List in R

A list is a specific vector type but can store mixed data types. In this example, we wanted to create a list with no elements and 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 replicating the values in the provided vector

A list is 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.

How to create empty list in R

To create an empty list in R, use the list() function and pass no parameter to the list() function call. 

empty_list <- list()
print(empty_list)

Output

list()

You can see that we created an empty list. To fill the elements in the list, use the append() function.

Creating an empty list using a vector in R

Using the vector() function, you can create an empty list in R. The vector() function takes two arguments: mode and length. The mode is a list, length is the number of elements in the list, and the list ends up 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. This is because 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. 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 nullable values, and it is significant 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 that returns when an expression or function results in an undefined value.

That is it.

See also

How to create an empty vector

How to create an empty Data Frame

Leave a Comment