10

One column of my data frame has words and phrases. I am trying to create a dummy variable for those fields within this column that have specific strings of text anywhere within.

For example:

  • kite
  • cars
  • box kites
  • model cars
  • i like kites that fly
  • cars of the world

     myvector<-c("kite","cars","box kites","model cars","i like kites that fly",
     "cars of the world")
    

I would want to identify all the fields with the string "kite"

I've tried a few things such as any(), which() and %in% but nothing has worked so far.

Any help greatly appreciated

0

1 Answer 1

33

You didn't provided any reproducible example. But your answer will be grepl.

grepl("kite", df$words)

It will return a logical vector if the word is in the row.

If you want to match multiple words use logical or | inside the string to match

grepl("kite|cars|box kites", df$words)
4
  • cool, this works really well. If I had 2 or more words would I just repeat this with another grepl()? I tried searching 2 words with grepl(c("word1","word2"),df$words) R didn't like that. I also tried it with grepl("word1"|"word2",df$words) and grepl("word1"||"word2",df$words) but no luck. I can do multiple grepl()'s. I don't have that many words but I thought I would ask. Sep 13, 2012 at 15:25
  • create 1 dummy variable (1 or 0) but there are a few words to search on that would get a "1". I can do grepl() for each word separately, sum the resulting vectors and ifelse a final vector if the sum is 0 then 0 else 1. Though if it could work in a single grepl() it's more efficient. Sep 13, 2012 at 15:33
  • oh, the | is inside the quotes. awesome! Thanks Sep 13, 2012 at 15:35
  • @willPhillips If you want to use a vector you could use grepl(paste0(c("word1","word2"), collapse='|'), df$words)
    – mikey
    Mar 9, 2022 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.