Khashir
Khashir

Reputation: 351

How to create a new column based on a regex match across all columns?

I want to search for a regex pattern across all my columns and if there's a match, create a new column with "Match", otherwise "No Match."

When filtering, I was able to do this with

filter_all(any_vars(str_detect(., '(?i)string.*c5')))

But when I tried

mutate(match = if_else(any_vars(str_detect(., '(?i)string.*c5')), "Match", "No Match"))

I get a

"condition must be a logical vector, not an any_vars object" error.

That makes sense, but I haven't figured out how to shuffle functions around to get it done. Note that not all my columns are strings, but hopefully that's not an issue.

I read through a few answers but none of those worked--c_across and rowsum didn't work either (used in other answer on the site).

Upvotes: 1

Views: 729

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389135

You may use if_any -

library(dplyr)
library(stringr)

data %>%
  mutate(match = if_else(if_any(.fns = ~str_detect(., '(?i)string.*c5')), "Match", "No Match"))

Upvotes: 1

Related Questions