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
– 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.
list1 = list("x", "y", "z")
list2 = list("A", "B", "C", "x", "y", "z")
print("Original lists are:")
## [1] "Original lists are:"
print(list1)
## [[1]]
## [1] "x"
##
## [[2]]
## [1] "y"
##
## [[3]]
## [1] "z"
print(list2)
## [[1]]
## [1] "A"
##
## [[2]]
## [1] "B"
##
## [[3]]
## [1] "C"
##
## [[4]]
## [1] "x"
##
## [[5]]
## [1] "y"
##
## [[6]]
## [1] "z"
print("All elements of list2 that are not in list1:")
## [1] "All elements of list2 that are not in list1:"
setdiff(list2, list1)
## [[1]]
## [1] "A"
##
## [[2]]
## [1] "B"
##
## [[3]]
## [1] "C"
list1 = list("A", "B", "C")
list2 = list("A", "B", "C", "x", "y", "z")
print("Original lists are:")
## [1] "Original lists are:"
print(list1)
## [[1]]
## [1] "A"
##
## [[2]]
## [1] "B"
##
## [[3]]
## [1] "C"
print(list2)
## [[1]]
## [1] "A"
##
## [[2]]
## [1] "B"
##
## [[3]]
## [1] "C"
##
## [[4]]
## [1] "x"
##
## [[5]]
## [1] "y"
##
## [[6]]
## [1] "z"
print("All elements of list2 that are not in list1:")
## [1] "All elements of list2 that are not in list1:"
setdiff(list2, list1)
## [[1]]
## [1] "x"
##
## [[2]]
## [1] "y"
##
## [[3]]
## [1] "z"