user1401333
user1401333

Reputation: 83

How to compare characters vectors for partial matches in R

This must be a simple question, but as an R newcomer I haven't been able to figure it out.

I have two character vectors, List1 and List2, and I would like to know how many of the samples in List1 are also found in List2. But List2 often has multiple names put together which seems to be messing things up. Here are the hypothetical lists:

List1 <- c("SampleX", "SampleY", "SampleZ", "SampleQ")

List2 <- c("SampleX", "SampleY", "Alias1,Alias2,SampleZ")

I can get an output that identifies SampleX and SampleY, but not SampleZ.

Any suggestions??

Thanks!!

Upvotes: 8

Views: 2009

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 227031

How about:

List1[sapply(List1,function(x) any(grepl(x,List2)))]
[1] "SampleX" "SampleY" "SampleZ"

?

Upvotes: 11

Related Questions