R Program to add a new item to a given list

How to add a new item to a given list

Here we are explaining how to write an R program to add a new item to a given list. Here we are using the given list for adding new items. The use of the $ symbol helps to specify the new item along with the list.

df$x

– where x indicates the position or element of the list df.

How to add a new item to a given list in the R program

Below are the steps used in the R program to add a new item to a given list. In this R program, we directly give the values to a list by specifying the element with the position. Consider the variable L1 which holds the list elements. And here adding a new element to the position x4.

ALGORITHM

  • STEP 1: Assign variables L1 with a list
  • STEP 2: Print the original lists
  • STEP 3: Add a new element to the list as L1$x4 = “Banana”
  • STEP 4: Print the final list L1

R Source Code

L1 = list(x1 = 1:5, x2 = "Apple", x3 = "Mango")

print("Original list:")
## [1] "Original list:"
print(L1)
## $x1
## [1] 1 2 3 4 5
## 
## $x2
## [1] "Apple"
## 
## $x3
## [1] "Mango"
print("Add a new vector to the list:")
## [1] "Add a new vector to the list:"
L1$x4 = "Banana"

print(L1)
## $x1
## [1] 1 2 3 4 5
## 
## $x2
## [1] "Apple"
## 
## $x3
## [1] "Mango"
## 
## $x4
## [1] "Banana"