Ferdi - 11 months ago 40

R Question

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

Answer

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
```

Source (Stackoverflow)