Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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) 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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading