Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R match part of string against vector of strings

Tags:

string

r

match

I have a comma separated character class

A = "123,456,789"

and I am trying to get a logical vector for when one of the items in the character class are present in a character array.

B <- as.array(c("456", "135", "789", "111"))

I am looking for logical result of size 4 (length of B)

[1] TRUE FALSE TRUE FALSE

Fairly new to R so any help would be appreciated. Thanks in advance.

like image 880
Keith D Avatar asked Feb 11 '23 20:02

Keith D


2 Answers

You can use a combination of sapply and grepl, which returns a logical if matched

 sapply(B, grepl, x=A)
like image 90
DMT Avatar answered Feb 14 '23 08:02

DMT


Since your comparison vector is comma-separated, you can use this as a non-looping method.

B %in% strsplit(A, ",")[[1]]
# [1]  TRUE FALSE  TRUE FALSE

And one other looping method would be to use Vectorize with grepl. This uses mapply internally.

Vectorize(grepl, USE.NAMES = FALSE)(B, A)
# [1]  TRUE FALSE  TRUE FALSE
like image 38
Rich Scriven Avatar answered Feb 14 '23 08:02

Rich Scriven