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

半世苍凉 提交于 2019-12-18 13:33:10

问题


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")


回答1:


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"



回答2:


! only works on logical vectors. B is not logical, which is what causes the error. Decomposing the steps you're trying to make will show you this (i.e. !B). In this case, you want to use %in% (or match).

A[!A %in% B]

To decompose the above code:

  1. A %in% B creates a logical vector that is TRUE for values of A that exist in B.
  2. !A %in% B negates (reverses) the logic in (1)
  3. A[!A %in% B] returns the vector of elements that are TRUE in (2)



回答3:


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)


来源:https://stackoverflow.com/questions/10298662/find-elements-not-in-smaller-character-vector-list-but-in-big-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!