0

Assuming I have a dataframe called items, and the first column is ItemNames. I'd like to go through each item in in items$ItemNames and check if they contain any of these words in:

words = c("apple","Apple","Pear","pear")

and if they do, replace the entire string with the word "confirmed".

What I've tried:

I used a combination of a for loop and if statement to do it but it failed:

search = function(x){
    words = c("apple","Apple","Pear","pear")
    for (i in length(x)){
        if (grepl(words, x[1][i]) == TRUE){  #where x[1][i] is the individual element in the ItemNames.
            x[1][i] = "confirmed"}
    }
}

search(items)

It didn't work. Ideally, I should have all the names in ItemNames replaced with "confirmed" if they contain any of the elements in words.

Qonl
  • 79
  • 1
  • 10
  • Were you trying to do exact matches or just partial matches? When asking for help you should include a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output. I think the duplicate answers your question but if not, edit your question to make your specific problem more clear and it can be re-opened. – MrFlick Sep 08 '17 at 16:09

1 Answers1

1

Using stringr:

library(stringr)

words <- c("apple", "Apple", "Pear", "pear")
pattern <- paste(words, collapse = "|")

dt <- data.frame(
  ItemNames = c("Superb apple", "Superb Pear", "Superb car"), 
  Cost = c(1, 2, 3),
  stringsAsFactors = FALSE
)

index <- str_detect(dt$ItemNames, regex(pattern))
dt[index,]$ItemNames <- "confirmed"
67342343
  • 816
  • 5
  • 11