JsDart
JsDart

Reputation: 183

Filtering dataframe on regex string across all rows?

I've read in a table df which has numbers and strings.

I have a keywords stored in a vector arr_words. For every row in the table; if row contains any word from the vector ignoring case, I want to keep that row.

For instance, if one of the cells has "i like magIcalot", and one of my keywords is "magic", I want to keep all the attributes from that row.

I've been trying this, but I'm pretty sure it's wrong since it's getting me back zero rows-

df %>%
  rowwise() %>% 
  filter(any(names(df) %in% arr_words))

Upvotes: 0

Views: 37

Answers (1)

Sonny
Sonny

Reputation: 3183

If you want to search in any specific field say field1, you can use as below:

library(dplyr)
df %>%
   filter(grepl(arr_words,field1))

If you want to search across all fields, then:

library(stringr)
library(dplyr)
df %>%
  filter_all(any_vars(str_detect(., arr_words)))

Upvotes: 3

Related Questions