The idea is to sequentially remove instances of keywords until I have only one instance of the keyword in the corresponding string.
You don't need a for
loop:
#split your strings by space
substrings <- strsplit(string, " ", fixed=TRUE)
#remove spaces from keywords
keyword_clean <- gsub("\\s", "", keyword)
#loop over the strings
sapply(substrings, function(s) {
#which word is duplicated and a keyword
rm <- which(duplicated(s, fromLast=TRUE) & s %in% keyword_clean)
#remove the duplicated keywords
if (length(rm > 0)) s <- s[-rm]
#paste words together
paste(s, collapse=" ")
})
#[1] " san temple lush" " mohito sudoku war" " metal martyr" " jump statement" " window capsule turn"