R Program to merge two given lists into one list


September 2, 2021, Learn eTutorial
739

How to merge two given lists into one list?

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

c(…) # Where ... indicates object to be concatenate

How to implement the merge algorithm in the R program

In this R program, we directly give the values to a built-in function c(). Here we are using variables lst1 and lst2 for holding the list elements of two different types. Call the function c() for merging the two lists and assigning them to a list variable merge_lst.

ALGORITHM

STEP 1: Assign variables lst1,lst2  with a list of two different types

STEP 2: Print the original lists

STEP 3: Merge the two lists by calling the combine function as c(lst1,lst2)

STEP 4: Assign merged lists into the variable merge_lst

STEP 5: Print the merged list merge_lst

R Source Code

                                          lst1 = list(5,2,1)
lst2 = list("Red", "Green", "Black")
print("Original lists:")
print(lst1)
print(lst2)
print("Merge the lists:")
merge_lst =  c(lst1, lst2)
print("New merged list:")
print(merge_lst)
                                      

OUTPUT

[1] "Original lists:"
[[1]]
[1] 5

[[2]]
[1] 2

[[3]]
[1] 1

[[1]]
[1] "Red"

[[2]]
[1] "Green"

[[3]]
[1] "Black"

[1] "Merge the lists:"
[1] "New merged list:"
[[1]]
[1] 5

[[2]]
[1] 2

[[3]]
[1] 1

[[4]]
[1] "Red"

[[5]]
[1] "Green"

[[6]]
[1] "Black"