Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find elements not in smaller character vector list but in big list

I have the two big and small list. I want to know which of the elements in big list are not in smaller list. The list consists of property

([1] "character"           "vector"              "data.frameRowLabels"
[4] "SuperClassMethod"

Here is small example and error I am getting

 A <- c("A", "B", "C", "D")
 B <- c("A", "B", "C")
  new <- A[!B]
Error in !B : invalid argument type

The expected output is new <- c("D")

like image 769
jon Avatar asked Apr 24 '12 13:04

jon


2 Answers

Look at help("%in%") - there's an example all the way at the bottom of that page that addresses this situation.

A <- c("A", "B", "C", "D")
B <- c("A", "B", "C")
(new <- A[which(!A %in% B)])

# [1] "D"

EDIT:

As Tyler points out, I should take my own advice and read the support documents. which() is unnecessary when using %in% for this example. So,

(new <- A[!A %in% B])

# [1] "D"
like image 198
BenBarnes Avatar answered Oct 06 '22 14:10

BenBarnes


While I think sets may help you to deal with different lists.

In your case, you can just use:

A <- c("A", "B", "C", "D")
B <- c("A", "B", "C")

# to find difference
setdiff(A, B)

# to find intersect
intersect(A, B)

# to find union
union(A, B)
like image 41
rankthefirst Avatar answered Oct 06 '22 14:10

rankthefirst