How to Create an Empty List in R (With Examples)


You can use the following syntax to create an empty list in R:

#create empty list with length of zero
empty_list <- list()

#create empty list of length 10
empty_list <- vector(mode='list', length=10)

The following examples show how to use these functions in practice.

Example 1: Create Empty List in R with Length of Zero

The following code shows how to create an empty list with a length of zero in R:

#create empty list
empty_list <- list()

#verify that empty_list is of class 'list'
class(empty_list)

[1] "list"

#view length of list
length(empty_list)

[1] 0

The result is a list with a length of 0.

Example 2: Create Empty List in R with Specific Length

The following code shows how to create an empty list of length 8 in R:

#create empty list of length 8
empty_list <- vector(mode='list', length=8)

#verify that empty_list is of class 'list'
class(empty_list)

[1] "list"

#view list
empty_list
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL

[[5]]
NULL

[[6]]
NULL

[[7]]
NULL

[[8]]
NULL

The result is a list with a length of 8 in which every element in the list is NULL.

Example 3: Append Values to Empty List in R

One of the most common reasons to create an empty list is to then fill it with values using a loop.

The following code shows how to create an empty list, then fill it with values:

#create empty list of length 8
empty_list <- vector(mode='list', length=8)

#get length of list
len <- length(empty_list)

#define values to append to list
new <- c(3, 5, 12, 14, 17, 18, 18, 20)

#fill values in list
i = 1
while(i <= length(new)) {
    empty_list[[i]] <- new[i]
    i <- i + 1
}

#display updated list
empty_list

[[1]]
[1] 3

[[2]]
[1] 5

[[3]]
[1] 12

[[4]]
[1] 14

[[5]]
[1] 17

[[6]]
[1] 18

[[7]]
[1] 18

[[8]]
[1] 20

Notice that the empty list is now filled with the new values that we specified.

Additional Resources

How to Create an Empty Data Frame in R
How to Append Values to List in R
How to Convert List to Vector in R

Leave a Reply

Your email address will not be published.