R Program to add a new item to a given list


March 1, 2022, Learn eTutorial
1297

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 a built-in function list() for this. This function helps to create a list. The syntax of this function is 

list(…) 

Where ....(dots)are the objects, possibly named.

How to add a new item to a given list using 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 built-in function list(). Here we are using variables L1 for holding the list elements g1,g2,g3. Call the function list() with different types of elements. Add the new item g4 with value 'Python' to the list L1 as like L1$g4 = "Python".

ALGORITHM

STEP 1: Assign variables L1 with a list

STEP 2: Create L1 with 3 sets of elements g1,g2,g3

STEP 3: Print the original lists

STEP 4: Add a new item g4 to the list as  L1$g4 = "Python"

STEP 5: Print the final list L1

R Source Code

                                          L1 = list(g1 = 1:5, g2 = "C Programming", g3 = "JAVA")
print("Original list:")
print(L1)
print("Add a new vector to the said list:")
L1$g4 = "Python"
print(L1)
                                      

OUTPUT

[1] "Original list:"
$g1
[1] 1 2 3 4 5

$g2
[1] "C Programming"

$g3
[1] "JAVA"

[1] "Add a new vector to the said list:"
$g1
[1] 1 2 3 4 5

$g2
[1] "C Programming"

$g3
[1] "JAVA"

$g4
[1] "Python"