title: Keep EXACT words from R corpus
body: <p>From answer posted on: Keep document ID with R corpus by @MrFlick </p>
  
  <p>I am trying to slightly modify what is a great example. </p>
  
  <p><strong>Question:</strong> How do I modify the <em><code>content_transformer</code> function</em> to keep only <strong>exact</strong> words? You can see in the inspect output that wonderful is counted as wonder and ratio is counted as rationale. I do not have a strong understanding of <code>gregexpr</code> and <code>regmatches</code>. </p>
  
  <p>Create data frame:</p>
  
  <pre><code>dd &lt;- data.frame(
    id = 10:13,
    text = c("No wonderful, then, that ever",
             "So that in many cases such a ",
             "But there were still other and",
             "Not even at the rationale")
    , stringsAsFactors = F
  )
  </code></pre>
  
  <p>Now, in order to read special attributes from a data.frame, we will use the <code>readTabular</code> function to make our own custom data.frame reader</p>
  
  <pre><code>library(tm)
  myReader &lt;- readTabular(mapping = list(content = "text", id = "id"))
  </code></pre>
  
  <p>specify the column to use for the contents and the id in the data.frame. Now we read it in with <code>DataframeSource</code> but use our custom reader.</p>
  
  <pre><code>tm &lt;- VCorpus(DataframeSource(dd), readerControl = list(reader = myReader))
  </code></pre>
  
  <p>Now if we want to only keep a certain set of words, we can create our own content_transformer function. One way to do this is</p>
  
  <pre><code>  keepOnlyWords &lt;- content_transformer(function(x, words) {
          regmatches(x, 
              gregexpr(paste0("\\b(",  paste(words, collapse = "|"), "\\b)"), x)
          , invert = T) &lt;- " "
          x
      })
  </code></pre>
  
  <p>This will replace everything that's not in the word list with a space. Note that you probably want to run <code>stripWhitespace</code> after this. Thus our transformations would look like</p>
  
  <pre><code>keep &lt;- c("wonder", "then", "that", "the")
  
  tm &lt;- tm_map(tm, content_transformer(tolower))
  tm &lt;- tm_map(tm, keepOnlyWords, keep)
  tm &lt;- tm_map(tm, stripWhitespace)
  </code></pre>
  
  <p>Inspect dtm matrix:</p>
  
  <pre><code>&gt; inspect(dtm)
  &lt;&lt;DocumentTermMatrix (documents: 4, terms: 4)&gt;&gt;
  Non-/sparse entries: 7/9
  Sparsity           : 56%
  Maximal term length: 6
  Weighting          : term frequency (tf)
  
      Terms
  Docs ratio that the wonder
    10     0    1   1      1
    11     0    1   0      0
    12     0    0   1      0
    13     1    0   1      0
  </code></pre>