How to Append to Empty List in R

R List is a data structure having items of different data types. You can append, update, or remove elements from the list. First, let’s see how to create an empty list and append an element to the list.

R append to empty list

To append to an empty list in R, use the append() function. The append() is a built-in list function that adds elements to a list. The append() method allows us to define where to append the values within the list.

To create an empty list in R, use the list() function.

empty_list <- list()
element <- list(a = 4)
appended_list <- append(empty_list, element)
print(appended_list)

Output

$a
[1] 4

In this example, we used the list() function to declare an empty list and then defined another list element using the list(a = 4) and appended that list to an empty list using the append() function.

By default, the append() method adds an element at the end of the list, but our initial list is empty, so it does not matter.

How to append a vector to an empty list in R

To append a vector to an empty list in R, use the append() function. Define an empty list, declare a vector with one element, and append that vector to a list using the append() function.

empty_list <- list()
element <- c("a")
appended_list <- append(empty_list, element)
print(appended_list)

Output

[[1]]
[1] "a"

To create a vector in R, use the c() function. We used the append() function to append a vector to an empty list, and based on the output, we successfully appended an element to the empty list.

That’s it.

Leave a Comment