R Program to merge two given lists into one list

How to merge two given lists into one list

Here we are explaining how to write an R program to merge two given lists into one list. Here we are using a built-in function c() for this. This function helps to combine its arguments to form a list in this all the arguments are coerced to a common type and it is the type of the returned value, The syntax of this function is

c(…) – where … indicates object to be concatenate

How to merge two given lists into one list in the R program

Below are the steps used in the R program to merge two given lists into one list. In this R program, we directly give the values to a built-in function c(). Here we are using variables l1,l2 for holding the list elements of two different types. Call the function c() for merging the two lists and assigned to variable li.

ALGORITHM

  • STEP 1: Assign variables l1,l2 with a list of two different types
  • STEP 2: Print the original lists
  • STEP 3: Merge the two lists by calling c() as c(l1,l2)
  • STEP 4: Assign merged lists into the variable li
  • STEP 5: Print the merged list li

R Source Code

l1 = list(5,2,1)
l2 = list("Red", "Green", "Black")

print("Original lists:")
## [1] "Original lists:"
print(l1)
## [[1]]
## [1] 5
## 
## [[2]]
## [1] 2
## 
## [[3]]
## [1] 1
print(l2)
## [[1]]
## [1] "Red"
## 
## [[2]]
## [1] "Green"
## 
## [[3]]
## [1] "Black"
print("Merge the lists:")
## [1] "Merge the lists:"
li =  c(l1, l2)

print("New merged list:")
## [1] "New merged list:"
print(li)
## [[1]]
## [1] 5
## 
## [[2]]
## [1] 2
## 
## [[3]]
## [1] 1
## 
## [[4]]
## [1] "Red"
## 
## [[5]]
## [1] "Green"
## 
## [[6]]
## [1] "Black"