Skip to contents
library(ggplot2)
library(dplyr)
library(tidyr)
library(g6tr.tm)
library(g6tr.theme)
data("ds_stopwords", package = 'g6tr.tm')

Text Mining Explained

Text mining is the process of deriving high-quality information from text. High-quality information is typically derived through the devising of patterns and trends through means such as statistical pattern learning. Text mining usually involves the process of:

  • structuring the input text (usually parsing, along with the addition of some derived linguistic features and the removal of others, and subsequent insertion into a database)
  • deriving patterns within the structured data
  • and finally evaluation and interpretation of the output.

‘High quality’ in text mining usually refers to some combination of relevance, novelty, and interest. Typical text mining tasks include text categorization, text clustering, concept/entity extraction, production of granular taxonomies, sentiment analysis, document summarization, and entity relation modeling (i.e., learning relations between named entities).

The overarching goal is, essentially, to turn text into data for analysis, via application of natural language processing (NLP) and analytical methods.

Gradient & Text Mining

At Gradient we occasionally need to dive into our text mining capabilities. For example, we have done a lot of work on the metaphor project, and developed a separate package for that as well.

In addition to our work on metaphor, we felt the need to add functions to our g6tr package wherever we see fit. This page will be updated every time we add a new text mining function, and will have the prefix tm_.

Current functionalities

Cleaning Text

some_text = "Hi!, This is just 1 stupid EXAMPLE to show clean.text :) [123-456-789]"
#default application
tm_clean_text(some_text)
[1] "hi this is just stupid example to show clean text"
tm_clean_text(some_text, lowercase = F)
[1] "Hi This is just stupid EXAMPLE to show clean text"
tm_clean_text(some_text, lowercase = F, punctuation = F)
[1] "Hi!, This is just stupid EXAMPLE to show clean.text :) [--]"
tm_clean_text(some_text, lemmatize = T)
[1] "hello this be just stupid example to show clean text"
tm_clean_text(some_text, remove_stopwords = T)
[1] "stupid show clean text"
tm_clean_text(some_text,
              lemmatize = T)
[1] "hello this be just stupid example to show clean text"
tm_clean_text(some_text,
              remove_stopwords = T)
[1] "stupid show clean text"

Counting an (n)gram

In the fields of computational linguistics and probability, an n-gram is a contiguous sequence of n items from a given sample of text or speech. The items can be phonemes, syllables, letters, words or base pairs according to the application. The n-grams typically are collected from a text or speech corpus. When the items are words, n-grams may also be called shingles.

Using Latin numerical prefixes, an n-gram of size 1 is referred to as a unigram; size 2 is a bigram; size 3 is a trigram.

We often use n-grams to find patterns and relations in unstructured test data.

Bigrams

library(janeaustenr)

df <- 
  austen_books() %>%
  dplyr::filter(book == "Sense & Sensibility")
 
bigram_count <- 
  tm_count_ngrams(
    df = df,
    var = "text",
    ngram = 2,
    remove_stopwords = TRUE,
    lemmatize = FALSE
  )

bigram_count %>% 
  head(10) %>%
  kable(align = 'l')
word1 word2 n
mrs jennings 214
colonel brandon 116
mrs dashwood 109
sir john 108
lady middleton 87
mrs ferrars 67
miss dashwood 58
john dashwood 35
mr palmer 34
mrs palmer 34

Trigrams

df <- 
  austen_books() %>%
  filter(book == "Sense & Sensibility")

trigram_count <- 
  tm_count_ngrams(
    df = df,
    var = "text",
    ngram = 3,
    remove_stopwords = TRUE,
    lemmatize = FALSE
  )

# Trigrams are way less common
trigram_count %>% 
  head(10) %>%
  kable(align = 'l')
word1 word2 word3 n
mrs john dashwood 20
cried mrs jennings 8
mr robert ferrars 5
cried sir john 4
dear miss dashwood 4
sir john middleton 4
dear dear norland 3
dear mrs jennings 3
lady middleton mother 3
miss lucy steele 3

Visualizing n-grams

if(Sys.info()['sysname'] == 'Darwin') {
  opts_chunk$set(eval = FALSE)
}

There are many ways to visualize n-grams, yet we like the network plots the most. It shows how the ngrams are connected with each other.

Bigrams

set.seed(2019)
tm_ngrams_plot(
  bigram_count, 
  max_ngrams = 35,
  edge_color = "#0078CD"
)

Trigrams

set.seed(2019)
tm_ngrams_plot(
  trigram_count, 
  max_ngrams = 35,
  edge_color = "#0078CD"
)

Co-occurrence Networks

Co-occurrence networks are generally used to provide a graphic visualization of potential relationships between people, organizations, concepts or other entities represented within written material.

By way of definition, co-occurrence networks are the collective interconnection of terms based on their paired presence within a specified unit of text. Networks are generated by connecting pairs of terms using a set of criteria defining co-occurrence. For example, terms A and B may be said to “co-occur” if they both appear in a particular article. Another article may contain terms B and C. Linking A to B and B to C creates a co-occurrence network of these three terms. Rules to define co-occurrence within a text corpus can be set according to desired criteria. For example, a more stringent criteria for co-occurrence may require a pair of terms to appear in the same sentence.

We’ve developed a function that finds co-occurrences and builds out a network object based on the network package.

df <- 
  austen_books() %>%
  filter(book == "Sense & Sensibility") %>%
  sample_n(1000)

# Create cooccurance network object
network <-
   tm_network(
     df,
     var = "text",
     weight = 'topN',
     n = 40,
     clean_text = TRUE,
     remove_stopwords = TRUE
    )

Next up, we can visualize the network with tm_network_plot(). This will return a ggplot object, making it easy to adjust.

if(Sys.info()['sysname'] != 'Darwin') {
  # Plot the network object with \link{ggnetwork}
  library(ggnetwork)
    
  plot <- tm_network_plot(network, range = c(4,8))
  
  plot
}

TF IDF

Term Frequency - Inverse Document Frequency (TF-IDF) is a statistic that is intended to reflect how important a word is to a document. When comparing different groups or cuts, it’s used to present which terms are dominant in one group, but not in others. It’s a great approach to surface terms and topics that are otherwise dominated by terms that are representative for all groups at the same time (e.g. in this report, it can surface regional differences, whereas they would otherwise be drowned out by common issues).

We can create a TF-IDF by passing the categorical variable and the text variable into the tm_tf_idf() function:

if(Sys.info()['sysname'] != 'Darwin') {
  df <- austen_books()
  
  tf_idf <- tm_tf_idf(df, var = "book", text_var = "text")
    
  tm_tf_idf_plot(tf_idf, N = 10) + 
    g6tr.theme::theme_g6tr(base_size = 15)
}