How to Append Values to List in R (With Examples)

Appending values to a list in R can be done using the c() or append() functions. The c() function combines the elements in a vector or list into a single vector, whereas the append() function adds elements to the end of a list. Examples of how to use both functions to append values to a list are provided.


You can use the following syntax to append a single value to a list in R:

#get length of list called my_list
len <- length(my_list)

#append value of 12 to end of list
my_list[[len+1]] <- 12

And you can use the following syntax to append multiple values to a list in R:

#get length of list called my_list
len <- length(my_list)

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

#append values to list
i = 1
while(i <= length(new)) {
    my_list[[i+len]] <- new[i]
    i <- i + 1
}

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

Example 1: Append a Single Value to a List

Suppose we have the following list in R:

#create list
my_list <- list(7, 14, c(1, 2, 3))

#view list
my_list

[[1]]
[1] 7

[[2]]
[1] 14

[[3]]
[1] 1 2 3

We can use the following syntax to append the value 12 to the end of the list:

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

#append value to end of list
my_list[[len+1]] <- 12

#view list
my_list

[[1]]
[1] 7

[[2]]
[1] 14

[[3]]
[1] 1 2 3

[[4]]
[1] 12

Example 2: Append Multiple Values to a List

Suppose we have the following list in R:

#create list
my_list <- list(7, 14, c(1, 2, 3))

#view list
my_list

[[1]]
[1] 7

[[2]]
[1] 14

[[3]]
[1] 1 2 3

We can use the following syntax to append several values to the end of the list:

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

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

#append values to list
i = 1
while(i <= length(new)) {
    my_list[[i+len]] <- new[i]
    i <- i + 1
}

#display updated list
my_list

[[1]]
[1] 7

[[2]]
[1] 14

[[3]]
[1] 1 2 3

[[4]]
[1] 3

[[5]]
[1] 5

[[6]]
[1] 12

[[7]]
[1] 14

x