w3resource

R Programming - Find elements in one List Not in another


Write a R program to find all elements of a given list that are not in another given list.

Sample Solution :

R Programming Code :

# Create the first list with elements "x", "y", "z"
l1 = list("x", "y", "z")

# Create the second list with elements "X", "Y", "Z", "x", "y", "z"
l2 = list("X", "Y", "Z", "x", "y", "z")

# Print a message indicating the original lists
print("Original lists:")

# Print the contents of the first list
print(l1)

# Print the contents of the second list
print(l2)

# Print a message indicating the result of finding elements in l2 that are not in l1
print("All elements of l2 that are not in l1:")

# Find and print elements of l2 that are not present in l1 using setdiff
setdiff(l2, l1)

Output:

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

[[2]]
[1] "y"

[[3]]
[1] "z"

[[1]]
[1] "X"

[[2]]
[1] "Y"

[[3]]
[1] "Z"

[[4]]
[1] "x"

[[5]]
[1] "y"

[[6]]
[1] "z"

[1] "All elements of l2 that are not in l1:"
[[1]]
[1] "X"

[[2]]
[1] "Y"

[[3]]
[1] "Z"                         

Explanation:

  • l1 = list("x", "y", "z"):
    • Creates a list l1 containing elements "x", "y", and "z".
  • l2 = list("X", "Y", "Z", "x", "y", "z"):
    • Creates a list l2 containing elements "X", "Y", "Z", "x", "y", and "z".
  • print("Original lists:"):
    • Prints the message "Original lists:" to indicate the following output shows the original lists.
  • print(l1):
    • Prints the contents of list l1.
  • print(l2):
    • Prints the contents of list l2.
  • print("All elements of l2 that are not in l1:"):
    • Prints the message "All elements of l2 that are not in l1:" to indicate the following output shows elements present in l2 but not in l1.
  • setdiff(l2, l1):
    • Finds and prints the elements that are in l2 but not in l1. This uses the setdiff function to identify differences between the two lists.

R Programming Code Editor:



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

Previous: Write a R program to get the length of the first two vectors of a given list.

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.