0

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))
JsDart
  • 183
  • 13

1 Answers1

3

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)))
Sonny
  • 3,083
  • 1
  • 11
  • 19
  • Thanks for the really quick reply! It works pretty well, but is not ignoring case when searching; is there any way to fix that? – JsDart Mar 13 '19 at 19:57
  • Try the comment [here](https://stackoverflow.com/questions/44530029/r-how-to-ignore-case-when-using-str-detect) – Sonny Mar 13 '19 at 20:00
  • It worked; thanks a lot! To anyone wondering, it's- ```df %>% filter_all(any_vars(str_detect(., regex(arr_words, ignore_case = T)))) ``` – JsDart Mar 13 '19 at 20:17