Home ยป How to Append Values to List in R (With Examples)

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

by Tutor Aspire

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

#get length of list called my_list
len 

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

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

#get length of list called my_list
len #define values to append to list
new #append values to list
i = 1
while(i 

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 #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 #append value to end of list
my_list[[len+1]] #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 #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 #define values to append to list
new #append values to list
i = 1
while(i #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

Additional Resources

How to Append Values to a Vector in R
How to Append Rows to a Data Frame in R

You may also like