Here we explain how to write an R program to find all elements of a given list that are not in another list. Here we are using a built-in function setdiff() for this. This function helps to calculate the set difference of subsets of a probability space or lists. The syntax of this function is
setdiff(x, y, …)
Where x and y are the vectors, data frames, or any R objects containing a sequence of items.
Below are the steps used in the R program to convert a given list to a vector. In this R program, we directly give the values to a built-in function setdiff(). Here we are using variables list1,list2 for holding the list elements. Call the function setdiff() for finding the extra elements in the list2. Finally, print the difference in the lists.
STEP 1: Assign variables list1,list2 with a lists
STEP 2: Print the original lists
STEP 3:Find the list difference by calling the function setdiff(list1,list2)
STEP 4: Print the list difference
list1 = list("x", "y", "z")
list2 = list("A", "B", "C", "x", "y", "z")
print("Original lists are:")
print(list1)
print(list2)
print("All elements of list2 that are not in list1:")
setdiff(list2, list1)
[1] "Original lists are:" [[1]] [1] "x" [[2]] [1] "y" [[3]] [1] "z" [[1]] [1] "A" [[2]] [1] "B" [[3]] [1] "C" [[4]] [1] "x" [[5]] [1] "y" [[6]] [1] "z" [1] "All elements of l2 that are not in l1:" [[1]] [1] "A" [[2]] [1] "B" [[3]] [1] "C"