title: Find documents with two words in a given proximity in R
body: <p>I have a dataframe with a variable called <code>text</code>, which includes news transcripts. I want to identify transcripts that include the word "Republican" OR "Democrat" AND one of a list of words in a given proximity (let's say within 5 words). For example, if one of the list of words is "Congress," I want to pick up these transcripts:</p>
  
  <ul>
  <li>"Republicans in Congress today voted on a bill." (proximity &lt; 5)</li>
  <li>"Democrats in Congress today voted on a bill." (proximity &lt; 5)</li>
  </ul>
  
  <p>And I do NOT want to pick up these transcripts:</p>
  
  <ul>
  <li>"Republicans today passed a bill to allocate funds for Congress." (proximity > 5)</li>
  <li>"Democrats today passed a bill to allocate funds for Congress." (proximity > 5)</li>
  </ul>
  
  <p>I can match the list of words without the proximity restraint like this:</p>
  
  <pre><code>transcripts &lt;- data.frame(text=c("Republicans in congress today voted on a bill","Republicans today passed a bill to allocate funds for Congress")
  dictionary &lt;- data.frame(word=c("Congress","Capitol"))
  
  transcripts_subset &lt;- transcripts %&gt;%
    filter(grepl(paste(dictionary$word, collapse="|"), text))
  </code></pre>
  
  <p>and I tried looking up the regex to do this correctly, but it throws an error:</p>
  
  <pre><code>transcripts_subset &lt;- transcripts %&gt;%
     filter(grepl("\b(paste(dictionary$dehumanizing, collapse="|"))(?:\\W+\\w+){0,5}?\\W+(Republican|Democrat)\b", text))
  </code></pre>
  
  <pre><code>Error in "\b ..." : 
    operations are possible only for numeric, logical or complex types
  </code></pre>
  
  <p>How can I make this work?</p>