w3resource

R Programming: Merge two given lists into One List


Write a R program to merge two given lists into one list.

Sample Solution :

R Programming Code :

# Create the first list containing numbers
n1 = list(1,2,3)

# Create the second list containing color names
c1 = list("Red", "Green", "Black")

# Print a message indicating the following output will be the original lists
print("Original lists:")

# Print the first list
print(n1)

# Print the second list
print(c1)

# Print a message indicating that the lists will be merged
print("Merge the said lists:")

# Merge the two lists into one
mlist =  c(n1, c1)

# Print a message indicating the following output will be the new merged list
print("New merged list:")

# Print the merged list
print(mlist)

Output:

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

[[2]]
[1] 2

[[3]]
[1] 3

[[1]]
[1] "Red"

[[2]]
[1] "Green"

[[3]]
[1] "Black"

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

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] "Red"

[[5]]
[1] "Green"

[[6]]
[1] "Black"                         

Explanation:

  • Create First List:
    • n1 = list(1,2,3)
      • Defines a list n1 containing the numbers 1, 2, and 3.
  • Create Second List:
    • c1 = list("Red", "Green", "Black")
      • Defines a list c1 containing the color names "Red", "Green", and "Black".
  • Print Original Lists Message:
    • print("Original lists:")
      • Prints a message indicating that the following output will display the original lists.
  • Print First List:
    • print(n1)
      • Outputs the contents of the list n1.
  • Print Second List:
    • print(c1)
      • Outputs the contents of the list c1.
  • Print Merge Message:
    • print("Merge the said lists:")
      • Prints a message indicating that the lists will be merged.
  • Merge Lists:
    • mlist = c(n1, c1)
      • Merges the lists n1 and c1 into a new list mlist.
  • Print New Merged List Message:
    • print("New merged list:")
      • Prints a message indicating that the following output will display the new merged list.
  • Print Merged List:
    • print(mlist)
      • Outputs the contents of the newly merged list mlist.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to create a list containing a vector, a matrix and a list and update the last element.
Next: Write a R program to convert a given list to vector.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.