Home > Mobile >  Compare two vectors and match only once if integer only appears once in vector
Compare two vectors and match only once if integer only appears once in vector

Time:12-21

I have two vectors that I want to compare. I have tried with match() and %in% but it does not give me the result I want. The solution should be in R base.

Input

   a = c(1,2,3,4,5)
   b = c(1,1,2)

Tested Solutions

b %in% a
TRUE TRUE TRUE

However, I want it to say TRUE FALSE TRUE, because "1" appears only once in a.

Is there any way of doing this in R Base?

CodePudding user response:

1) Append " 1" to the first occurrence of each entry, " 2" to the second and so on. Then use those.

f <- function(x) paste(x, seq_along(x))
ave(b, b, FUN = f) %in% ave(a, a, FUN = f)
## [1]  TRUE FALSE  TRUE

2) There are no dupliates in a in the example and if this is the case then another approach is check whether each element of b is in a but reject it if is it a duplicate.

(b %in% a) & !duplicated(b)
## [1]  TRUE FALSE  TRUE

Note

a <- c(1, 2, 3, 4, 5);  b <- c(1, 1, 2)  # inputs
  •  Tags:  
  • r
  • Related