# [R] finding those elements of listA that are found in listB

Richard M. Heiberger rmh at temple.edu
Thu Sep 17 05:33:22 CEST 2015

```I think you are looking for match or %in% (which is a based on match)

> a <- sample(12)
> b <- c(1, 3, 5, 11, 17)
> a
[1] 10  8  1  4  7  3  6 11  2 12  5  9
> b
[1]  1  3  5 11 17
> [1] 1
> match(a, b)
[1] NA NA  1 NA NA  2 NA  4 NA NA  3 NA
> match(a, b, 0)
[1] 0 0 1 0 0 2 0 4 0 0 3 0
> match(b, a)
[1]  3  6 11  8 NA
> match(b, a, 0)
[1]  3  6 11  8  0
> a %in% b
[1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE FALSE FALSE  TRUE FALSE
> b %in% a
[1]  TRUE  TRUE  TRUE  TRUE FALSE
>

Rich

On Wed, Sep 16, 2015 at 10:43 PM, John Sorkin <JSorkin at grecc.umaryland.edu>
wrote:

> I have two structures. I think they are lists, but I am not sure. Both
> structures contain integers. I am trying to find those members of list b
> that are found in list a. I have tried to perform the search using grep,
> but I get an error. Please see code below. I would appreciate knowing how
> to search listB for any element in listA
> Thanks
> John
>
>
> > str(listA)
>  int [1:42] 13083 13705 14123 14168 14382 14652 14654 14678 14817 14822 ...
> > str(listB)
>  int [1:633] 13083 13083 13083 13083 13083 13083 13705 13705 13705 13705
> ...
> > grep(listA,listB)
> [1] 1 2 3 4 5 6
> Warning message:
> In grep(listA, listB) :
>   argument 'pattern' has length > 1 and only the first element will be used
>
>
>
>
>
>
>
>
>
> John David Sorkin M.D., Ph.D.
> Professor of Medicine
> Chief, Biostatistics and Informatics
> University of Maryland School of Medicine Division of Gerontology and
> Geriatric Medicine
> Baltimore VA Medical Center
> 10 North Greene Street
> GRECC (BT/18/GR)
> Baltimore, MD 21201-1524
> (Phone) 410-605-7119
> (Fax) 410-605-7913 (Please call phone number above prior to faxing)
>
>
> Confidentiality Statement:
> This email message, including any attachments, is for ...{{dropped:16}}

```