title: Extract and count common word-pairs from character vector
body: <p>How can someone find frequent pairs of adjacent words in a character vector?  Using the crude data set, for example, some common pairs are "crude oil", "oil market", and "million barrels".</p>
  
  <p>The code for the small example below tries to identify frequent terms and then, using a positive lookahead assertion, count how many times those frequent terms are followed immediately by a frequent term.  But the attempt crashed and burned.</p>
  
  <p>Any guidance would be appreciated as to how to create a data frame that shows in the first column ("Pairs") the common pairs and in the second column ("Count") the number of times they appeared in the text. </p>
  
  <pre><code>   library(qdap)
     library(tm)
  
  # from the crude data set, create a text file from the first three documents, then clean it
  
  text &lt;- c(crude[[1]][1], crude[[2]][1], crude[[3]][1])
  text &lt;- tolower(text)
  text &lt;- tm::removeNumbers(text)
  text &lt;- str_replace_all(text, "  ", "") # replace double spaces with single space
  text &lt;- str_replace_all(text, pattern = "[[:punct:]]", " ")
  text &lt;- removeWords(text, stopwords(kind = "SMART"))
  
  # pick the top 10 individual words by frequency, since they will likely form the most common pairs
  freq.terms &lt;- head(freq_terms(text.var = text), 10) 
  
  # create a pattern from the top words for the regex expression below
  freq.terms.pat &lt;- str_c(freq.terms$WORD, collapse = "|")
  
  # match frequent terms that are followed by a frequent term
  library(stringr)
  pairs &lt;- str_extract_all(string = text, pattern = "freq.terms.pat(?= freq.terms.pat)")
  </code></pre>
  
  <p>Here is where the effort falters.</p>
  
  <p>Not knowing Java or Python, these did not help <a href="https://stackoverflow.com/questions/16096682/count-word-pairs-java">Java count word pairs</a> <a href="https://stackoverflow.com/questions/26414623/combine-count-of-word-pairs-python">Python count word pairs</a> but they may be useful references for others.</p>
  
  <p>Thank you.</p>