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

Adams, Jean jvadams at usgs.gov
Thu Sep 17 19:39:41 CEST 2015


John,

The intersect() function may help you.  For example:

listA <- sort(sample(10, 5))
listB <- sort(sample(10, 5))
both <- intersect(listA, listB)

> listA
[1] 2 4 7 8 9
> listB
[1]  1  2  3  8 10
> both
[1] 2 8

Jean

On Wed, Sep 16, 2015 at 9: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}}



More information about the R-help mailing list