R compare multiple values with vector and return vector [duplicate]
I have a vector "A", and for each element of A I want to check whether it is equal to any element from a second vector "Targets". I want a vector of logical values with the length of A as return.
The same problem is mentioned here. Here is a related discussion of how to test if a vector contains a specific value, but I did not know how to apply this to my question because I want a vector as output and not a single boolean.
Here is example code:
#example data
A <- c(rep("A",4),rep(c("B","C"),8))
Targets <- c("A","C","D")
I would like a vector which tells me for each element of A if it is equal to at least one of the elements in Targets. For the example, this should produce a vector that is identical with:
result <- c(rep("TRUE",4), rep(c("FALSE","TRUE"), 8))
In case this is relevant, eventually vector A will be much longer (ca 20000 elements), and the vector Targets will contain approximately 30 elements.
Solution 1:
Just try:
A %in% Targets
The %in%
function tells you if each element of the first argument equals one of the elements of the second argument, that's exactly what you are looking for.