title: R: gsub only if negation occurs within n letters before the target
body: <p>I am working on a primitive speech analysis algorithm. Now I want to improve how it handles negations of positive/negative statements. At the moment I add the string "NOT_" only if the negation directly occurs:</p>
  
  <pre><code>s_commentsOut$gsubContent &lt;- gsub("not ","not NOT_",gsub("n't ","n't NOT_",s_commentsOut$lowCo))
  </code></pre>
  
  <p>So for example</p>
  
  <pre><code>"This is not good"
  </code></pre>
  
  <p>becomes</p>
  
  <pre><code>"This is not NOT_good"
  </code></pre>
  
  <p>Now I want to achieve that the "NOT_" is also added when there are n characters in between the vector of target words and the negation, e.g.:</p>
  
  <pre><code>targetList &lt;- c("nice", "perfect", "good", "love")
  </code></pre>
  
  <p>Now with the help of the above list, the following string:</p>
  
  <pre><code>"This isn't a very good way"
  </code></pre>
  
  <p>should become</p>
  
  <pre><code>"This isn't a very NOT_good way"
  </code></pre>
  
  <p>This replacement should only take place if the negation occurs <code>n</code> (for instance <code>15</code>) characters before the target, e.g. the following should not be converted (because the distance between the target and the negation is <code>&gt; 15</code>):</p>
  
  <pre><code>"This is not going to work. However you did this very nicely."
  </code></pre>
  
  <p>I found the following SO articles:
  <a href="https://stackoverflow.com/questions/32764256/negation-of-several-characters-before-pattern">Negation of several characters before pattern</a></p>
  
  <p><a href="https://stackoverflow.com/questions/36556528/how-to-replace-a-character-in-a-string-but-only-if-it-occurs-within-a-delimited">How to replace a character in a string but only if it occurs within a delimited substring?</a></p>
  
  <p>But I struggle to get it right. In the meantime I help myself with removing strings like "like ", "an ", "a " from the text... </p>
  
  <p>Further Testphrases:</p>
  
  <p><code>"Nottingham is the love of my life."</code></p>
  
  <p><code>"This is good. Nottingham is a town."</code></p>
  
  <p><code>"This is not very good"</code></p>
  
  <p><code>"This is not good. This is not good. This is not very good. This is nice. This very nice. This is not very nice."</code></p>