Ferdi
Ferdi

Reputation: 560

How do I include a regular expression in a function in R?

below I wrote a function which searches for specific regular expressions within a vector. The function always searches for regular expressions including "Beer" or "Wine" within a vector. Now I would like to include the regular Expressions I am searching for (In my case "Beer and Wine") as additional variables into the vector. How can I do this?

x <- c("Beer","Wine","wine","Beer","Beef","Potato","Vacation") 
Thirsty <- function(x) {
Beer <-  grepl("Beer",x, ignore.case = TRUE)
Beer <- as.numeric(Beer == "TRUE")
Wine <-  grepl("Wine",x, ignore.case = TRUE)
Wine <- as.numeric(Wine == "TRUE")
Drink <- Beer + Wine
Drink <- as.numeric(Drink == "0")
Drink <-  abs(Drink -1)
}
    y <- Thirsty(x)
    y

Upvotes: 0

Views: 810

Answers (3)

Akhil Nair
Akhil Nair

Reputation: 3284

This should also work

Thirsty = function(vec, ...) {
  pattern = paste0(unlist(list(...)), collapse = "|")
  stringr::str_detect(tolower(vec), pattern)
}

> Thirsty (x, "beer", "wine")
[1]  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE    

Upvotes: 1

Deena
Deena

Reputation: 6213

I would simply try to concatenate the match patterns with |

strings = c("Beer","Wine","wine","Beer","Beef","Potato","Vacation") 
thirstStrings = c("beer", "wine")

matchPattern = paste0(thirstStrings, collapse = "|") #"beer|wine"
grep(pattern = matchPattern, x = strings, ignore.case = T)
# [1] 1 2 3 4

You can easily wrap that in a function

Thirsty = function(x, matchStrings){
  matchPattern = paste0(matchStrings, collapse = "|") #"beer|wine"
  grep(pattern = matchPattern, x = x, ignore.case = T)
}

Thirsty(strings, thirstStrings) # [1] 1 2 3 4

Upvotes: 1

Miff
Miff

Reputation: 7941

This can be done with the following code:

x <- c("Beer","Wine","wine","Beer","Beef","Potato","Vacation") 
drinks <- c("Beer","Wine")
Thirsty <- function(x, drinks) {
  Reduce("|",lapply(drinks, function(p)grepl(p,x, ignore.case = TRUE)))
}
y <- Thirsty(x,drinks)
y

lapply loops over the possibilities in drinks and produces a list of logical vectors, one for each drink. These are combined into a single vector by Reduce.

Upvotes: 1

Related Questions