R: substituting only whole statements (not parts of them) I have a data set DS.
I want to substitute the statements contained with others following a pattern-replacement schema like the following one:



I have used the followng function:

from_distincts_to_origins &lt;- function(patternST, replacementST,originalFile){

  #---------------------------------------
  patternST&lt;-paste0('\\b',patternST,'\\b')
  #---------------------------------------
  # we have to point back to the original data set
  file_origin_DF &lt;- as.data.frame(originalFile)

  file_output &lt;- file_origin_DF
  for(i in 1:length(patternST))   { 
    where &lt;- file_output[[1]]#vector
    file_output &lt;- apply(file_output,  
                         2,
                         function(x) sub(patternST[i], 
                                         replacementST[i], 
                                         where, 
                                         #ignored.case=FALSE, 
                                         perl=FALSE, 
                                         fixed=FALSE, useBytes=FALSE)
    )

    file_output &lt;- as.data.frame(file_output, stringsAsFactors =F) # in order to work
  }       

  return(file_output)
}


What will happen is that R will start substituting all the "I like football" with "football". When it will pass to the second row it will look for "I like football, W Lazio" but it will only find "football, W Lazio", so those rows won't be substituted with "Lazio".

One possible solution is to order the Pattern such to have the longest strings at the top, but it would only reduce the substitution missings.

Is there another method in R to do that?
I believe it will help if you add the exact regex anchors to the pattern you are trying to match. In your case adding "^I like football$" as the pattern you are trying to match will look for strings starting and ending exactly like that. That way you have:   

&gt;grepl("^I like football$", "I like football, W Lazio")
[1] FALSE


This will eliminate at least the problem you are facing now.
 I am not sure if I understand the rest of the question though...as I get it, you have some other character vector called text for example, and inside you are trying to look for elements of the vector pattern and, if matched, replace them with the corresponding vector element from replacement right?