Reputation: 3805
I have a string like this
fileName <- 'tyi_myRef_2019_2020'
I want to check if any of the following characters
are present in the fileName
and if yes, assign it to an object.
myChar <- c('myPer','myRef','myYe','myQr')
The way I did this is:
if(grepl('myPer', fileName)) {myObject <- 'myPer'}
if(grepl('myRef', fileName)) {myObject <- 'myRef'}
if(grepl('myYe', fileName)) {myObject <- 'myYe'}
if(grepl('myQr', fileName)) {myObject <- 'myQr'}
myObject
"myRef"
Is there a shorter way to do this?
Upvotes: 0
Views: 228
Reputation: 39667
You can use sapply
like:
myObject <- myChar[sapply(myChar, function(x) {grepl(x, fileName)})]
myObject
#[1] "myRef"
or even shorter as @g-grothendieck suggested:
myObject <- myChar[sapply(myChar, grepl, fileName)]
In case you have more than one hit myObject
will hold all hits, what is not the case with your if
statements, which will overwrite. With myObject[length(myObject)]
you will get the last hit like you do with the if
's.
You can also use |
in the regex and get the match like:
myObject <- sub(paste0(".*(", paste(myChar, collapse="|"), ").*"), "\\1", fileName)
Upvotes: 2
Reputation: 887148
An option is to paste
them into a single string collapse
by |
and feed that as pattern
in grepl
. The |
will act as OR
to check if any of the substrings are present in the 'fileName'
grepl(paste(myChar, collapse="|"), fileName)
Or another option is to extract
library(stringr)
str_extract(fileName, paste(myChar, collapse = "|"))
#[1] "myRef"
If wee need to assign, then
myChar[lengths(sapply(myChar, function(x) grep(x, fileName))) > 0]
#[1] "myRef"
Upvotes: 1
Reputation: 13319
With stringr
:
res<-stringr::str_extract_all(fileName,myChar)
res[lengths(res)>0]
[[1]]
[1] "myRef"
With base
:
res<-Map(function(x,y) x[grep(x,y)],myChar,fileName)
res[lengths(res)>0]
$myRef
[1] "myRef"
Upvotes: 1