Skip to content
Related Articles

Related Articles

How to Append Values to List in R?

Improve Article
Save Article
Like Article
  • Last Updated : 28 Nov, 2021

In this article, we will discuss how to append values to List in R Programming Language.

Method 1: Append a Single Value to a List

Here we are having an created list with some elements and we are going to append  a single value to list using [[]].

Syntax:

list1[[length(list1)+1]] = value

where,

  • list1 is the input list
  • value is the value to be appended
  • length[list1)+1 is to append a value at the last

Example: R program to append 12 to the list

R




# create a list of integers
list1 = list(c(1, 2, 3, 4, 5))
  
# display
print(list1)
  
print("---------")
  
# add element 12 to the list using length()
list1[[length(list1)+1]] = 12
  
# display
list1

Output:

[[1]]
[1] 1 2 3 4 5

[1] "---------"
[[1]]
[1] 1 2 3 4 5

[[2]]
[1] 12

Method 2: Append Multiple Values to a List

Here we are going to append the multiple values to the existing list using for loop.

Syntax:

for ( i in values){
    list1[[length(list1)+1]] = i
}

where,

  • values are the values in a vector to be appended

Example:

R




# create list1
list1 = list(c(1, 2, 3, 4, 5), 223)
  
# create a vector to append these values to list
values = c(100, 200, 300)
  
# append values to list
for (i in values){
    list1[[length(list1)+1]] = i
}
  
# display final list
list1

Output:

[[1]]
[1] 1 2 3 4 5

[[2]]
[1] 223

[[3]]
[1] 100

[[4]]
[1] 200

[[5]]
[1] 300

Method 3: Using append() function

This function is used to append values to the list at last by using append() function.

Syntax:

append(list,values)

where,

  • list is the input list
  • values are the values in a vector to be appended

Example:

R




# create list1
list1 = list(c(1, 2, 3, 4, 5), 223)
  
# create a vector to append these values to list
values = c(100, 200, 300)
  
# display final list
append(list1, values)

Output:

[[1]]
[1] 1 2 3 4 5

[[2]]
[1] 223

[[3]]
[1] 100

[[4]]
[1] 200

[[5]]
[1] 300

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!