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
.
Using
stringr
: