Hands-On Data Science with R
Text Mining

Graham.Williams@togaware.com

5th November 2014

Visit http://HandsOnDataScience.com/ for more Chapters.

library(tm)
library(SnowballC)
library(qdap)
library(qdapDictionaries)
library(dplyr)
library(RColorBrewer)
library(ggplot2)
library(scales)
library(Rgraphviz)

Text Mining or Text Analytics applies analytic tools to learn from collections of text documents
like books, newspapers, emails, etc. The goal is similar to humans learning by reading books.
Using automated algorithms we can learn from massive amounts of text, much more than a human
can. The material could be consist of millions of newspaper articles to perhaps summarise the
main themes and to identify those that are of most interest to particular people.

The required packages for this module include:

# Framework for text mining.
# Provides wordStem() for stemming.
# Quantitative discourse analysis of transcripts.

D R A F T

# Data preparation and pipes %>%.
# Generate palette of colours for plots.
# Plot word frequencies.
# Include commas in numbers.
# Correlation plots.

As we work through this chapter, new R commands will be introduced. Be sure to review the
command’s documentation and understand what the command does. You can ask for help using
the ? command as in:
?read.csv

We can obtain documentation on a particular package using the help= option of library():

library(help=rattle)

This chapter is intended to be hands on. To learn e↵ectively, you are encouraged to have R
running (e.g., RStudio) and to run all the commands as they appear here. Check that you get
the same output, and you understand the output. Try some variations. Explore.

Copyright
2013-2014 Graham Williams. You can freely copy, distribute,
or adapt this material, as long as the attribution is retained and derivative
work is provided under the same license.

Data Science with R

Hands-On

Text Mining

1 Loading a Corpus

A corpus is a collection of texts, usually stored electronically, and from which we perform our
analysis. A corpus might be a collection of news articles from Reuters or the published works of
Shakespeare. Within each corpus we will have separate articles, stories, volumes, each treated
as a separate entity or record.

Documents which we wish to analyse come in many di↵erent formats. Quite a few formats are
supported by tm (Feinerer and Hornik, 2014), the package we will illustrate text mining with in
this module. The supported formats include text, PDF, Microsoft Word, and XML.

A number of open source tools are also available to convert most document formats to text ﬁles.
For our corpus used initially in this module, a collection of PDF documents were converted to text
using pdftotext from the xpdf application which is available for GNU/Linux and MS/Windows
and others. On GNU/Linux we can convert a folder of PDF documents to text with:

system("for f in *.pdf; do pdftotext -enc ASCII7 -nopgbrk $f; done")

The -enc ASCII7 ensures the text is converted to ASCII since otherwise we may end up with
binary characters in our text documents.

We can also convert Word documents to text using anitword, which is another application
available for GNU/Linux.

system("for f in *.doc; do antiword $f; done")

D R A F T

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 1 of 40

Data Science with R

Hands-On

Text Mining

1.1 Corpus Sources and Readers

There are a variety of sources supported by tm. We can use getSources() to list them.

getSources()

## [1] "DataframeSource" "DirSource"
## [5] "XMLSource"

"URISource"

"VectorSource"

In addition to di↵erent kinds of sources of documents, our documents for text analysis will come
in many di↵erent formats. A variety are supported by tm:

getReaders()

## [1] "readDOC"
## [3] "readPlain"
## [5] "readRCV1asPlain"
## [7] "readReut21578XMLasPlain" "readTabular"
## [9] "readXML"

"readPDF"
"readRCV1"
"readReut21578XML"

D R A F T

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 2 of 40

Data Science with R

Hands-On

Text Mining

1.2 Text Documents

We load a sample corpus of text documents. Our corpus consists of a collection of research
papers all stored in the folder we identify below. To work along with us in this module, you
can create your own folder called corpus/txt and place into that folder a collection of text
documents. It does not need to be as many as we use here but a reasonable number makes it
more interesting.

cname <- file.path(".", "corpus", "txt")
cname

## [1] "./corpus/txt"

We can list some of the ﬁle names.

There are 46 documents in this particular corpus.

After loading the tm (Feinerer and Hornik, 2014) package into the R library we are ready to load
the ﬁles from the directory as the source of the ﬁles making up the corpus, using DirSource().
The source object is passed on to Corpus() which loads the documents. We save the resulting
collection of documents in memory, stored in a variable called docs.

length(dir(cname))

## [1] 46

dir(cname)

## [1] "acnn96.txt"
## [2] "adm02.txt"
## [3] "ai02.txt"
## [4] "ai03.txt"
....

D R A F T

## <<VCorpus (documents: 46, metadata (corpus/indexed): 0/0)>>

library(tm)
docs <- Corpus(DirSource(cname))
docs

class(docs)

## [1] "VCorpus" "Corpus"

class(docs[[1]])

## [1] "PlainTextDocument" "TextDocument"

summary(docs)

##
## acnn96.txt
## adm02.txt
## ai02.txt
....

Length Class
2
2
2

Mode
PlainTextDocument list
PlainTextDocument list
PlainTextDocument list

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 3 of 40

Data Science with R

Hands-On

Text Mining

1.3 PDF Documents

If instead of text documents we have a corpus of PDF documents then we can use the readPDF()
reader function to convert PDF into text and have that loaded as out Corpus.

docs <- Corpus(DirSource(cname), readerControl=list(reader=readPDF))

This will use, by default, the pdftotext command from xpdf to convert the PDF into text
format. The xpdf application needs to be installed for readPDF() to work.

D R A F T

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 4 of 40

Data Science with R

Hands-On

Text Mining

1.4 Word Documents

A simple open source tool to convert Microsoft Word documents into text is antiword. The
separate antiword application needs to be installed, but once it is available it is used by tm to
convert Word documents into text for loading into R.

To load a corpus of Word documents we use the readDOC() reader function:

docs <- Corpus(DirSource(cname), readerControl=list(reader=readDOC))

Once we have loaded our corpus the remainder of the processing of the corpus within R is then
as follows.

The antiword program takes some useful command line arguments. We can pass these through
to the program from readDOC() by specifying them as the character string argument:

docs <- Corpus(DirSource(cname), readerControl=list(reader=readDOC("-r -s")))

Here, -r requests that removed text be included in the output, and -s requests that text hidden
by Word be included.

D R A F T

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 5 of 40

Data Science with R

Hands-On

Text Mining

2 Exploring the Corpus

We can (and should) inspect the documents using inspect(). This will assure us that data has
been loaded properly and as we expect.

inspect(docs[16])

## <<VCorpus (documents: 1, metadata (corpus/indexed): 0/0)>>
##
## [[1]]
## <<PlainTextDocument (metadata: 7)>>
## Hybrid weighted random forests for
## classifying very high-dimensional data
## Baoxun Xu1 , Joshua Zhexue Huang2 , Graham Williams2 and
## Yunming Ye1
## 1
##
## Department of Computer Science, Harbin Institute of Technology Shenzhen Gr...
## School, Shenzhen 518055, China
## 2
## Shenzhen Institutes of Advanced Technology, Chinese Academy of Sciences, S...
## 518055, China
## Email: amusing002@gmail.com
## Random forests are a popular classification method based on an ensemble of a
## single type of decision trees from subspaces of data. In the literature, t...
## are many different types of decision tree algorithms, including C4.5, CART...
## CHAID. Each type of decision tree algorithm may capture different information
## and structure. This paper proposes a hybrid weighted random forest algorithm,
## simultaneously using a feature weighting method and a hybrid forest method to
## classify very high dimensional data. The hybrid weighted random forest alg...
## can effectively reduce subspace size and improve classification performance
## without increasing the error bound. We conduct a series of experiments on ...
## high dimensional datasets to compare our method with traditional random fo...
....

D R A F T

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 6 of 40

Data Science with R

Hands-On

Text Mining

3 Preparing the Corpus

We generally need to perform some pre-processing of the text data to prepare for the text anal-
ysis. Example transformations include converting the text to lower case, removing numbers and
punctuation, removing stop words, stemming and identifying synonyms. The basic transforms
are all available within tm.

getTransformations()

## [1] "removeNumbers"
## [4] "stemDocument"

"removePunctuation" "removeWords"
"stripWhitespace"

The function tm map() is used to apply one of these transformations across all documents within
a corpus. Other transformations can be implemented using R functions and wrapped within
content transformer() to create a function that can be passed through to tm map(). We will
see an example of that in the next section.

In the following sections we will apply each of the transformations, one-by-one, to remove un-
wanted characters from the text.

D R A F T

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 7 of 40

Data Science with R

Hands-On

Text Mining

3.1 Simple Transforms

We start with some manual special transforms we may want to do. For example, we might want
to replace “/”, used sometimes to separate alternative words, with a space. This will avoid the
two words being run into one string of characters through the transformations. We might also
replace “@” and “|” with a space, for the same reason.

To create a custom transformation we make use of content transformer() crate a function to
achieve the transformation, and then apply it to the corpus using tm map().

toSpace <- content_transformer(function(x, pattern) gsub(pattern, " ", x))
docs <- tm_map(docs, toSpace, "/")
docs <- tm_map(docs, toSpace, "@")
docs <- tm_map(docs, toSpace, "

|")

\\

\\

|")

inspect(docs[16])

This can be done with a single call:

Check the email address in the following.

docs <- tm_map(docs, toSpace, "/|@|

D R A F T

## <<VCorpus (documents: 1, metadata (corpus/indexed): 0/0)>>
##
## [[1]]
## <<PlainTextDocument (metadata: 7)>>
## Hybrid weighted random forests for
## classifying very high-dimensional data
## Baoxun Xu1 , Joshua Zhexue Huang2 , Graham Williams2 and
## Yunming Ye1
## 1
##
## Department of Computer Science, Harbin Institute of Technology Shenzhen Gr...
## School, Shenzhen 518055, China
## 2
## Shenzhen Institutes of Advanced Technology, Chinese Academy of Sciences, S...
## 518055, China
## Email: amusing002 gmail.com
## Random forests are a popular classification method based on an ensemble of a
## single type of decision trees from subspaces of data. In the literature, t...
## are many different types of decision tree algorithms, including C4.5, CART...
## CHAID. Each type of decision tree algorithm may capture different information
## and structure. This paper proposes a hybrid weighted random forest algorithm,
## simultaneously using a feature weighting method and a hybrid forest method to
## classify very high dimensional data. The hybrid weighted random forest alg...
## can effectively reduce subspace size and improve classification performance
## without increasing the error bound. We conduct a series of experiments on ...
## high dimensional datasets to compare our method with traditional random fo...
....

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 8 of 40

Data Science with R

Hands-On

Text Mining

3.2 Conversion to Lower Case

docs <- tm_map(docs, content_transformer(tolower))

inspect(docs[16])

## <<VCorpus (documents: 1, metadata (corpus/indexed): 0/0)>>
##
## [[1]]
## <<PlainTextDocument (metadata: 7)>>
## hybrid weighted random forests for
## classifying very high-dimensional data
## baoxun xu1 , joshua zhexue huang2 , graham williams2 and
## yunming ye1
## 1
##
## department of computer science, harbin institute of technology shenzhen gr...
## school, shenzhen 518055, china
## 2
## shenzhen institutes of advanced technology, chinese academy of sciences, s...
## 518055, china
## email: amusing002 gmail.com
## random forests are a popular classification method based on an ensemble of a
## single type of decision trees from subspaces of data. in the literature, t...
## are many different types of decision tree algorithms, including c4.5, cart...
## chaid. each type of decision tree algorithm may capture different information
## and structure. this paper proposes a hybrid weighted random forest algorithm,
## simultaneously using a feature weighting method and a hybrid forest method to
## classify very high dimensional data. the hybrid weighted random forest alg...
## can effectively reduce subspace size and improve classification performance
## without increasing the error bound. we conduct a series of experiments on ...
## high dimensional datasets to compare our method with traditional random fo...
....

D R A F T

General character processing functions in R can be used to transform our corpus. A common
requirement is to map the documents to lower case, using tolower(). As above, we need to
wrap such functions with a content transformer():

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 9 of 40

Data Science with R

Hands-On

Text Mining

3.3 Remove Numbers

docs <- tm_map(docs, removeNumbers)

inspect(docs[16])

## <<VCorpus (documents: 1, metadata (corpus/indexed): 0/0)>>
##
## [[1]]
## <<PlainTextDocument (metadata: 7)>>
## hybrid weighted random forests for
## classifying very high-dimensional data
## baoxun xu , joshua zhexue huang , graham williams and
## yunming ye
##
##
## department of computer science, harbin institute of technology shenzhen gr...
## school, shenzhen , china
##
## shenzhen institutes of advanced technology, chinese academy of sciences, s...
## , china
## email: amusing gmail.com
## random forests are a popular classification method based on an ensemble of a
## single type of decision trees from subspaces of data. in the literature, t...
## are many different types of decision tree algorithms, including c., cart, and
## chaid. each type of decision tree algorithm may capture different information
## and structure. this paper proposes a hybrid weighted random forest algorithm,
## simultaneously using a feature weighting method and a hybrid forest method to
## classify very high dimensional data. the hybrid weighted random forest alg...
## can effectively reduce subspace size and improve classification performance
## without increasing the error bound. we conduct a series of experiments on ...
## high dimensional datasets to compare our method with traditional random fo...
....

D R A F T

Numbers may or may not be relevant to our analyses. This transform can remove numbers
simply.

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 10 of 40

Data Science with R

Hands-On

Text Mining

3.4 Remove Punctuation

docs <- tm_map(docs, removePunctuation)

inspect(docs[16])

china

## <<VCorpus (documents: 1, metadata (corpus/indexed): 0/0)>>
##
## [[1]]
## <<PlainTextDocument (metadata: 7)>>
## hybrid weighted random forests for
## classifying very highdimensional data
## baoxun xu joshua zhexue huang graham williams and
## yunming ye
##
##
## department of computer science harbin institute of technology shenzhen gra...
## school shenzhen
##
## shenzhen institutes of advanced technology chinese academy of sciences she...
## china
## email amusing gmailcom
## random forests are a popular classification method based on an ensemble of a
## single type of decision trees from subspaces of data in the literature there
## are many different types of decision tree algorithms including c cart and
## chaid each type of decision tree algorithm may capture different information
## and structure this paper proposes a hybrid weighted random forest algorithm
## simultaneously using a feature weighting method and a hybrid forest method to
## classify very high dimensional data the hybrid weighted random forest algo...
## can effectively reduce subspace size and improve classification performance
## without increasing the error bound we conduct a series of experiments on e...
## high dimensional datasets to compare our method with traditional random fo...
....

D R A F T

Punctuation can provide gramatical context which supports understanding. Often for initial
analyses we ignore the punctuation. Later we will use punctuation to support the extraction of
meaning.

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 11 of 40

Data Science with R

Hands-On

Text Mining

3.5 Remove English Stop Words

docs <- tm_map(docs, removeWords, stopwords("english"))

inspect(docs[16])

technology shenzhen graduate

advanced technology chinese academy sciences shenzhen

china

## <<VCorpus (documents: 1, metadata (corpus/indexed): 0/0)>>
##
## [[1]]
## <<PlainTextDocument (metadata: 7)>>
## hybrid weighted random forests
## classifying highdimensional data
## baoxun xu joshua zhexue huang graham williams
## yunming ye
##
##
## department computer science harbin institute
## school shenzhen
##
## shenzhen institutes
## china
## email amusing gmailcom
## random forests
## single type decision trees
## many different types decision tree algorithms including c cart
## chaid
## structure paper proposes hybrid weighted random forest algorithm
## simultaneously using
## classify high dimensional data
## can effectively reduce subspace size
## without increasing
## high dimensional datasets
....

D R A F T

popular classification method based

length(stopwords("english"))

feature weighting method

We can list the stop words:

error bound

literature

subspaces

ensemble

conduct

series

type

data

hybrid forest method

hybrid weighted random forest algorithm
improve classification performance
experiments

eight

decision tree algorithm may capture different information

compare method traditional random forest

Stop words are common words found in a language. Words like for, very, and, of, are, etc, are
common stop words. Notice they have been removed from the above text.

## [1] 174

stopwords("english")

[1] "i"
[6] "our"

##
##
## [11] "yours"
## [16] "his"
....

"me"
"ours"
"yourself"
"himself"

"myself"

"my"
"ourselves" "you"
"yourselves" "he"
"she"

"her"

"we"
"your"
"him"
"hers"

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 12 of 40

Data Science with R

Hands-On

Text Mining

3.6 Remove Own Stop Words

docs <- tm_map(docs, removeWords, c("department", "email"))

inspect(docs[16])

advanced technology chinese academy sciences shenzhen

china

computer science harbin institute technology shenzhen graduate

## <<VCorpus (documents: 1, metadata (corpus/indexed): 0/0)>>
##
## [[1]]
## <<PlainTextDocument (metadata: 7)>>
## hybrid weighted random forests
## classifying highdimensional data
## baoxun xu joshua zhexue huang graham williams
## yunming ye
##
##
##
## school shenzhen
##
## shenzhen institutes
## china
## amusing gmailcom
## random forests
## single type decision trees
## many different types decision tree algorithms including c cart
## chaid
## structure paper proposes hybrid weighted random forest algorithm
## simultaneously using
## classify high dimensional data
## can effectively reduce subspace size
## without increasing
## high dimensional datasets
....

D R A F T

popular classification method based

feature weighting method

error bound

literature

subspaces

ensemble

conduct

series

type

data

hybrid forest method

hybrid weighted random forest algorithm
improve classification performance
experiments

eight

Previously we used the English stopwords provided by tm. We could instead or in addition
remove our own stop words as we have done above. We have chosen here two words, simply
for illustration. The choice might depend on the domain of discourse, and might not become
apparent until we’ve done some analysis.

decision tree algorithm may capture different information

compare method traditional random forest

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 13 of 40

Data Science with R

Hands-On

Text Mining

3.7 Strip Whitespace

docs <- tm_map(docs, stripWhitespace)

inspect(docs[16])

## <<VCorpus (documents: 1, metadata (corpus/indexed): 0/0)>>
##
## [[1]]
## <<PlainTextDocument (metadata: 7)>>
## hybrid weighted random forests
## classifying highdimensional data
## baoxun xu joshua zhexue huang graham williams
## yunming ye
##
##
## computer science harbin institute technology shenzhen graduate
## school shenzhen china
##
## shenzhen institutes advanced technology chinese academy sciences shenzhen
## china
## amusing gmailcom
## random forests popular classification method based ensemble
## single type decision trees subspaces data literature
## many different types decision tree algorithms including c cart
## chaid type decision tree algorithm may capture different information
## structure paper proposes hybrid weighted random forest algorithm
## simultaneously using feature weighting method hybrid forest method
## classify high dimensional data hybrid weighted random forest algorithm
## can effectively reduce subspace size improve classification performance
## without increasing error bound conduct series experiments eight
## high dimensional datasets compare method traditional random forest
....

D R A F T

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 14 of 40

Data Science with R

Hands-On

Text Mining

3.8 Speciﬁc Transformations

We might also have some speciﬁc transformations we would like to perform. The examples here
may or may not be useful, depending on how we want to analyse the documents. This is really
for illustration using the part of the document we are looking at here, rather than suggesting
this speciﬁc transform adds value.

toString <- content_transformer(function(x, from, to) gsub(from, to, x))
docs <- tm_map(docs, toString, "harbin institute technology", "HIT")
docs <- tm_map(docs, toString, "shenzhen institutes advanced technology", "SIAT")
docs <- tm_map(docs, toString, "chinese academy sciences", "CAS")

inspect(docs[16])

## <<VCorpus (documents: 1, metadata (corpus/indexed): 0/0)>>
##
## [[1]]
## <<PlainTextDocument (metadata: 7)>>
## hybrid weighted random forests
## classifying highdimensional data
## baoxun xu joshua zhexue huang graham williams
## yunming ye
##
##
## computer science HIT shenzhen graduate
## school shenzhen china
##
## SIAT CAS shenzhen
## china
## amusing gmailcom
## random forests popular classification method based ensemble
## single type decision trees subspaces data literature
## many different types decision tree algorithms including c cart
## chaid type decision tree algorithm may capture different information
## structure paper proposes hybrid weighted random forest algorithm
## simultaneously using feature weighting method hybrid forest method
## classify high dimensional data hybrid weighted random forest algorithm
## can effectively reduce subspace size improve classification performance
## without increasing error bound conduct series experiments eight
## high dimensional datasets compare method traditional random forest
....

D R A F T

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 15 of 40

Data Science with R

Hands-On

Text Mining

3.9 Stemming

library(SnowballC)
docs <- tm_map(docs, stemDocument)

Notice we load the SnowballC (Bouchet-Valat, 2014) package which provides stemming.

inspect(docs[16])

## <<VCorpus (documents: 1, metadata (corpus/indexed): 0/0)>>
##
## [[1]]
## <<PlainTextDocument (metadata: 7)>>
## hybrid weight random forest
## classifi highdimension data
## baoxun xu joshua zhexu huang graham william
## yunm ye
##
##
## comput scienc HIT shenzhen graduat
## school shenzhen china
##
## SIAT CAS shenzhen
## china
## amus gmailcom
## random forest popular classif method base ensembl
## singl type decis tree subspac data literatur
## mani differ type decis tree algorithm includ c cart
## chaid type decis tree algorithm may captur differ inform
## structur paper propos hybrid weight random forest algorithm
## simultan use featur weight method hybrid forest method
## classifi high dimension data hybrid weight random forest algorithm
## can effect reduc subspac size improv classif perform
## without increas error bound conduct seri experi eight
## high dimension dataset compar method tradit random forest
....

D R A F T

Stemming uses an algorithm that removes common word endings for English words, such as
“es”, “ed” and “’s”. The functionality for stemming is provided by wordStem() from SnowballC
(Bouchet-Valat, 2014).

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 16 of 40

Data Science with R

Hands-On

Text Mining

4 Creating a Document Term Matrix

A document term matrix is simply a matrix with documents as the rows and terms as the columns
and a count of the frequency of words as the cells of the matrix. We use DocumentTermMatrix()
to create the matrix:

dtm <- DocumentTermMatrix(docs)
dtm

## <<DocumentTermMatrix (documents: 46, terms: 6508)>>
## Non-/sparse entries: 30061/269307
## Sparsity
## Maximal term length: 56
## Weighting

: term frequency (tf)

: 90%

We can inspect the document term matrix using inspect(). Here, to avoid too much output,
we select a subset of inspect.

The document term matrix is in fact quite sparse (that is, mostly empty) and so it is actually
stored in a much more compact representation internally. We can still get the row and column
counts.

inspect(dtm[1:5, 1000:1005])

## <<DocumentTermMatrix (documents: 5, terms: 6)>>
## Non-/sparse entries: 7/23
## Sparsity
## Maximal term length: 9
....

: 77%

D R A F T

"simple_triplet_matrix"

class(dtm)

## [1] "DocumentTermMatrix"

dim(dtm)

## [1]

46 6508

The transpose is created using TermDocumentMatrix():

tdm <- TermDocumentMatrix(docs)
tdm

## <<TermDocumentMatrix (terms: 6508, documents: 46)>>
## Non-/sparse entries: 30061/269307
## Sparsity
## Maximal term length: 56
## Weighting

: term frequency (tf)

: 90%

We will use the document term matrix for the remainder of the chapter.

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 17 of 40

Data Science with R

Hands-On

Text Mining

5 Exploring the Document Term Matrix

We can obtain the term frequencies as a vector by converting the document term matrix into a
matrix and summing the column counts:

freq <- colSums(as.matrix(dtm))
length(freq)

## [1] 6508

By ordering the frequencies we can list the most frequent terms and the least frequent terms:

ord <- order(freq)

# Least frequent terms
freq[head(ord)]

## aaaaaaeaceeaeeieaeaeeiiaiaciaiicaiaeaeaoeneiacaeaaeooooo
1
##
aab
##
1
##
aadrbltn
##
##
1
aadrhtmliv
##
1
##
aai
##
##
1
....

D R A F T

can dataset pattern
887
776
709

data
3101

use
1366

mine
1446

##
##

Notice these terms appear just once and are probably not really terms that are of interest to us.
Indeed they are likely to be spurious terms introduced through the translation of the original
document from PDF to text.
# Most frequent terms
freq[tail(ord)]

These terms are much more likely to be of interest to us. Not surprising, given the choice
of documents in the corpus, the most frequent terms are: data, mine, use, pattern, dataset,
can.

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 18 of 40

Data Science with R

Hands-On

Text Mining

6 Distribution of Term Frequencies

# Frequency of frequencies.
head(table(freq), 15)

## freq
3
1
##
## 2381 1030 503

2

4
311

5
210

6

7
188 134

8
130

9
82

10
83

11
65

12
61

13
54

14
52

15
51

tail(table(freq), 15)

## freq
## 483 544 547
1
##

1

1

555 578
1

1

609 611
1

1

616 703
1

1

709
1

776 887 1366 1446 3101
1

1

1

1

1

So we can see here that there are 2381 terms that occur just once.

Generate a plot of term frequency.

D R A F T

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 19 of 40

Data Science with R

Hands-On

Text Mining

7 Conversion to Matrix and Save to CSV

We can convert the document term matrix to a simple matrix for writing to a CSV ﬁle, for
example, for loading the data into other software if we need to do so. To write to CSV we ﬁrst
convert the data structure into a simple matrix:

m <- as.matrix(dtm)
dim(m)

## [1]

46 6508

For very large corpus the size of the matrix can exceed R’s calculation limits. This will manifest
itself as a integer overﬂow error with a message like:

## Error in vector(typeof(x$v), nr * nc) : vector size cannot be NA
## In addition: Warning message:
## In nr * nc : NAs produced by integer overflow

If this occurs, then consider removing sparse terms from the document term matrix, as we discuss
shortly.

Once converted into a standard matrix the usual write.csv() can be used to write the data to
ﬁle.

write.csv(m, file="dtm.csv")

D R A F T

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 20 of 40

Data Science with R

Hands-On

Text Mining

8 Removing Sparse Terms

We are often not interested in infrequent terms in our documents. Such “sparse” terms can be
removed from the document term matrix quite easily using removeSparseTerms():

dim(dtm)

## [1]

46 6508

dtms <- removeSparseTerms(dtm, 0.1)
dim(dtms)

## [1] 46

6

This has removed most terms!

inspect(dtms)

## <<DocumentTermMatrix (documents: 46, terms: 6)>>
## Non-/sparse entries: 257/19
## Sparsity
## Maximal term length: 7
....

: 7%

We can see the e↵ect by looking at the terms we have left:

time
483

use william
236

D R A F T

1366

1

freq <- colSums(as.matrix(dtms))
freq

inform
467

##
##

data
3101

graham
108

table(freq)

## freq
## 108 236 467
1
##

1

1

483 1366 3101
1

1

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 21 of 40

Data Science with R

Hands-On

Text Mining

9

Identifying Frequent Items and Associations

One thing we often to ﬁrst do is to get an idea of the most frequent terms in the corpus. We use
findFreqTerms() to do this. Here we limit the output to those terms that occur at least 1,000
times:

findFreqTerms(dtm, lowfreq=1000)

## [1] "data" "mine" "use"

So that only lists a few. We can get more of them by reducing the threshold:

findFreqTerms(dtm, lowfreq=100)

"age"
"angioedema"
"associ"
"averag"

We can also ﬁnd associations with a word, specifying a correlation limit.

findAssocs(dtm, "data", corlimit=0.6)

[1] "accuraci"
[6] "algorithm"

##
##
## [11] "appli"
## [16] "attribut"
....

##
## mine
## induct
## challeng
....

data
0.90
0.72
0.70

"acsi"
"allow"
"applic"
"australia"

"adr"
"also"
"approach"
"australian"

"advers"
"analysi"
"area"
"avail"

D R A F T

If two words always appear together then the correlation would be 1.0 and if they never appear
together the correlation would be 0.0. Thus the correlation is a measure of how closely associated
the words are in the corpus.

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 22 of 40

Data Science with R

Hands-On

Text Mining

10 Correlations Plots

current

databas

dataset

contain

combin

common

cost

compar

case

consid

call

can

data

claim

consist

cluster

attribut

chang

area

analysi

decis

comput

collect

classifi

classif

build

class

confer

algorithm

accuraci

plot(dtm,

also

avail

appli

base

allow

applic

condit

associ

australia

australian

angioedema

D R A F T

approach

averag

advers

csiro

care

age

day

adr

acsi

terms=findFreqTerms(dtm, lowfreq=100)[1:50],
corThreshold=0.5)

Rgraphviz (Gentry et al., 2014) from the BioConductor repository for R (bioconductor.org) is
used to plot the network graph that displays the correlation between chosen words in the corpus.
Here we choose 50 of the more frequent words as the nodes and include links between words
when they have at least a correlation of 0.5.

By default (without providing terms and a correlation threshold) the plot function chooses a
random 20 terms with a threshold of 0.7.

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 23 of 40

Data Science with R

Hands-On

Text Mining

11 Correlations Plot—Options

current

databas

dataset

contain

combin

common

cost

compar

case

consid

call

can

data

claim

consist

cluster

attribut

chang

area

analysi

decis

comput

collect

classifi

classif

build

class

confer

algorithm

accuraci

plot(dtm,

also

avail

appli

base

allow

applic

condit

associ

australia

australian

angioedema

D R A F T

approach

averag

advers

csiro

care

age

day

adr

acsi

terms=findFreqTerms(dtm, lowfreq=100)[1:50],
corThreshold=0.5)

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 24 of 40

Data Science with R

Hands-On

Text Mining

12 Plotting Word Frequencies

We can generate the frequency count of all words in a corpus:

freq <- sort(colSums(as.matrix(dtm)), decreasing=TRUE)
head(freq, 14)

data
3101

mine
1446
cluster algorithm
611

616

##
##
##
##
....

use
1366
rule
609

pattern
887
featur
578

dataset
776
set
555

can
709
tree
547

model
703
method
544

<- data.frame(word=names(freq), freq=freq)

wf
head(wf)

##
## data
## mine
## use
....

word freq
data 3101
mine 1446
use 1366

library(ggplot2)
subset(wf, freq>500)

We can then plot the frequency of those words that occur at least 500 times in the corpus:

ggplot(aes(word, freq))
geom_bar(stat="identity")
theme(axis.text.x=element_text(angle=45, hjust=1))

%>%
+
+

D R A F T

3000

2000

q
e
r
f

1000

0

algorith m

can

cluster

data

dataset

featur

m ethod

mine

m odel

pattern

rule

set

tree

use

word

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 25 of 40

Data Science with R

Hands-On

Text Mining

13 Word Clouds

better

particular

reason
find
second

section
clear
indic
unit
accord
techniqu

l

t
a
p
m
e
t

artifici

supp

l

four
a
c
o

l

publish
make

som
open

identifi
might

need

benefit
investig

level
public

fraud
equat

l

e
d
o
m
nugget

obtain

clinic
final
consist
grow
d
o
h
rare
t
area
e
m
m
a
text

i

program
strength

emerg

r
u
s
a
e
m

well
present
world

analysi
extract

huang

rang
contain

choos
inform
occur
natur
user
must
build
ieee
categor
describ
p
creat
becom
a
m
recent
higher

optim
practic

worker

outcom

view

requir

prototyp

classif
support

suppa

t
e
g
connect
r
a
step
t
graham
interesting
class

perform

paper

length

shown

develop
repres

manag
may
search

specifi

relat
togeth

automat
messag
structur
valid
applic
statist
one
descript
appear

transact
interact
export
risk
produc
standard

l

stage
u
a
v

t
r
o
p
o
r
p

activ
therefor
averag
advantag
definit

determin

mani
age
help
purpos
machin
start
real
outlier
current
review
press

employ
breiman
issu
node
year
increas
sinc
conclus
output
esophag
instal

item

divers
weight
period
upon
engin

i

i
l

i

t
h
g

h
g
h

i
r
e
v
o
c
s
d
evalu
deploy
subset
event
smyth
addit

framework

best
also
correl
test
ratio
p
m
a
x
e

l

miss
singl
prune
assess
train

sourc

w
o

similar
top
cca
o
f
intern

l
l

r
e
v
o
c

address

densiti
match

i

s
n
a
g
r
o
chosen

i
r
o
t
a
r
o
b
a

l

expert
experi
main
remain
avail

built

spatial

combin
improv

correspond

inhibitor

propos

simpli
debian

domain

possibl
actual
order
minimum
gap

leverag
cart
servic
random
differ
system

preadmiss
give

commonwealth
function
piatetskyshapiro

i

n
a
g

suggest
residualleverag
depend

tune

select
comparison
expect

contextdata

even

tabl

studi
drug

algorithm
intellig

hadi
within

general
understand

rnn

t
r
a
p

reaction

accuraci
total
first
australian
see
popul

evolutionari
decis

use

mutarc

offic

appropri
independ

estim

construct

experiment

major

patholog

confid

alendron
probabl
altern

project

refer
input
now

i

d
d
n
a
c

group
much
link
r
o
e
t
r
c
g
e
e
v
d

e
s
a
c

deliv
introduct

insur
log
methodolog
quit
new
receiv
month

igi
distribut
predict
acsi
split
larger
rather
hot
transform
set
mml
market
entiti

tradit
induct
classifi

i
r
o
e
h
t

ensembl

calcul
sequenc
dataset
less
high

hidden
busi
observ
databas
premium
var
complex
tar
varieti element
compon
adr
line
consider
effect
govern
caa
environ
time
fit
whole miner
mean
angioedema

defin
move

due
gnu

locat

t
h
g
i
r

end

run

l
l
i
t
s

n
e
v
g

i

softwar
e
g
a
p

exclus
n
o

i
l
l
i

m

l

l

i

i

i

i
l

o

t

i
l

file

e
k

next

mbs

r
u
t
u
f

http

w
o
h
s

femal

hepat

action

overal

author

diseas

analys

among

normal

distinct

s
s
m
d
a

without

continu

visualis

s
n
o
p
s
e
r

paramet

frequenc

journal

distanc

geograph

d
e
e
c
o
r
p

characterist

t
c
e
p
x
e
n
u

list
specif

allow
introduc

exposur
prior

parallel
visual

attribut
network

illustr
consid

type
seri
oper

basic
known
anoth

t
o
p
s
count

d
o
o
g
involv

gis
success

threshold
individu

health
compar

n
r
e

t
i
episod
t
r
a
ace
p
utar
version
exist

demonstr
factor
sampl

hazard
problem

generat
lead

linux
t
o
p
form
key
pbs

interest
doctor

discuss
n
a
t
r
e
c

detect
subspac

common
interfac
smaller
prepar

deriv
d
r
o
c
e
r
s
u
c
o
f

t
t
a
p
concept
object

will
interpret
typic
a
r
u
appli
e
n

advers
base
act
direct
rattl

forward
difficult
abl
region
various
reduc

score
situat
william
medic
scheme

t
a
x
a
t
begin
term
advanc
howev

mine

csiro
behaviour
discov
technolog
respect

postdischarg
low
window point

o
f
t
r
o
p
represent
suitabl
previous gender

limit
vol
subsequ
consequ
made intrus
graphic
matrix

copyright
found
field
tempor
import

learn
administr
task
process
small

interv
thus
architectur
drg
call
monitor
kdd
o
w

multipl
usag
condit
rank
mathemat
tmip
summari
layer

ann
confer
tree
approach
occurr
queensland
e
d
o
c
categori

n
g
s
e
d
plane
posit
chen
error
cluster
state
rule
separ
hospit

cost
complet
custom
control
patient
preprocess
way
hybrid
medicar
acm
tool
explor
collect

can
care
scienc
segment
three
includ
simpl
result
frequent
claim
report
stream
donohostahel
access
knowledg
rate
day
fig
variabl
pmml
initi
provid

D R A F T

research
number
detail

regular
teffici
c
a
r
t
s
b
a

insight
note
remov
n
g
i
r
o

languag
implement
space

least
comput

literatur
figuroften

featur

captur
packag

c
o
s
s
a

larg

sequenti

a
e
d

i

i

i

regress
forest
australia
nation
dimension

sever
global
chang
usual
work

industri
univers
size

polici

take

s
e
y
goal

canberra

signific

The wordcloud (?) package provides the required function.

library(wordcloud)
set.seed(123)
wordcloud(names(freq), freq, min.freq=40)

Notice the use of set.seed() only so that we can obtain the same layout each time—otherwise
a random layout is chosen, which is not usually an issue.

We can generate a word cloud as an e↵ective alternative to providing a quick visual overview of
the frequency of words in a corpus.

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 26 of 40

Data Science with R

Hands-On

Text Mining

13.1 Reducing Clutter With Max Words

model
section
set
present
inform

method
techniqu
relat

insur

data

support

will

mani
train

outlier

structur

h
c
a
o
group
r
p
g
associ
p
u
a
includ
r
studi
d
number
cluster
generat
identifi
time
health
high

record
class
process
can

perform

u
a
v

l

describ

featur

general

use

test
differ
similar
new

work
comput
may
tree
select
random

rule

d
o
i
r
e
p

databas
figur
servic

popul
learn

provid

paper
also
function
first
develop
e
n
m

forest
system
larg
sequenc
variabl

pattern

l

t

i

e
n
o

william

event

m
e
b
o
r
p

r
u
s
a
e
m

base
applic

t
c
e
t
e
d
exampl

research
sourc
tabl
analysi
classif

case
patient
user
distribut
knowledg
kdd
risk
discoveri
map
o
w

t
e
s
a
t
a
d
decis
statist
interest
algorithm
tempor

D R A F T

result

To increase or reduce the number of words displayed we can tune the value of max.words=. Here
we have limited the display to the 100 most frequent words.

set.seed(142)
wordcloud(names(freq), freq, max.words=100)

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 27 of 40

Data Science with R

Hands-On

Text Mining

13.2 Reducing Clutter With Min Freq

unit

group
rule
type
collect
interest
visual
discov
graham

avail
scienc

multipl

also

medic

estim

decis
problem
tree
contain
forest

observ
effici
journal
size
one
requir

n
e

t
f

o

object

interv
develop

within
expect
structur
neural
can
sourc

defin

care
generat

refer
research

will
may

dataset
cluster
use

discoveri

predict
system
approach

kdd
number

howev
classif
sequenc
occur
appli
node

t
r
e
p
x
e
http

signific

intern
advers

report

pattern
drug
record
databas
implement

t
c
e
t
e
d

present

risk
relat
sampl

mean

l
t
t

a
r

first

regress
exampl
network

i

outlier
base
total
function
state
explor
repres
consist
includ
adr
random
import
call
d
n
a

angioedema
csiro
condit
stage
t
s
x
e
make
hot
s
s
r
e
a
p
c
o
univers
year
averag

t
r
o
p
p
u
s

l

chang

weight

increas
high
target

need

confer
open
hybrid
usual

algorithm
train
page
particular
transact
process
insur
well
ratio
figur
distribut
result
intellig
t
s
i
t
a
t
s

featur
paper
build
acsi
tempor
search
user

william
variabl
inform
combin
tabl
subset
level
method
g
rnn
r
individu
a
fig
perform
evalu
section
event
a
step
m
work
lead
s
attribut select
form
measur
analysi area

utar
like
link

i
t

hospit
identifi
discuss
accuraci
n
a
m
o
d

l
l

l

i

i

singl

classifi

order

given

d
u
t
s

new

window

t
s
r
e
d
n
u

servic

e
m

describ

interesting

find
follow

applic
machin

two
current
learn

comput
techniqu

indic
compar
three

vector
entiti
p
a
m

australia
case
technolog

australian
proceed
popul
test

show
reaction
age
experi
mani
similar

model
consid
associ

effect
rank
error
distanc
tool
subspac

t
s
o
c
propos
day
general
allow

patient
unexpect
d
o
i
r
e
p
claim
differ
health
point
packag

data
mine

D R A F T

knowledg

t
e
s

provid
pmml
valu
common
task

nugget

polici
episod
spot

A more common approach to increase or reduce the number of words displayed is by tuning the
value of min.freq=. Here we have limited the display to those words that occur at least 100
times.

set.seed(142)
wordcloud(names(freq), freq, min.freq=100)

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 28 of 40

Data Science with R

Hands-On

Text Mining

13.3 Adding Some Colour

unit

group
rule
type
collect
interest
visual
discov
graham

avail
scienc

multipl

also

medic

estim

decis
problem
tree
contain
forest

observ
effici
journal
size
one
requir

n
e

t
f

o

object

interv
develop

within
expect
structur
neural
can
sourc

defin

care
generat

refer
research

will
may

dataset
cluster
use

discoveri

predict
system
approach

kdd
number

howev
classif
sequenc
occur
appli
node

t
r
e
p
x
e
http

signific

intern
advers

report

pattern
drug
record
databas
implement

t
c
e
t
e
d

present

risk
relat
sampl

mean

l
t
t

a
r

first

regress
exampl
network

i

outlier
base
total
function
state
explor
repres
consist
includ
adr
random
import
call
d
n
a

angioedema
csiro
condit
stage
t
s
x
e
make
hot
s
s
r
e
a
p
c
o
univers
year
averag

t
r
o
p
p
u
s

l

l

chang

weight

increas
high
target

need

confer
open
hybrid
usual

algorithm
train
page
particular
transact
process
insur
well
ratio
figur
distribut
result
intellig
t
s
i
t
a
t
s

featur
paper
build
acsi
tempor
search
user

william
variabl
inform
combin
tabl
subset
level
method
g
rnn
r
individu
a
fig
perform
evalu
section
event
a
step
m
work
lead
s
attribut select
form
measur
analysi area

utar
like
link

e
m

hospit
identifi
discuss
accuraci
n
a
m
o
d

l
l

i

i

i
t

singl

classifi

order

given

d
u
t
s

new

window

t
s
r
e
d
n
u

servic

describ

interesting

find
follow

applic
machin

two
current
learn

comput
techniqu

indic
compar
three

vector
entiti
p
a
m

australia
case
technolog

australian
proceed
popul
test

show
reaction
age
experi
mani
similar

model
consid
associ

effect
rank
error
distanc
tool
subspac

t
s
o
c
propos
day
general
allow

patient
unexpect
d
o
i
r
e
p
claim
differ
health
point
packag

data
mine

D R A F T

knowledg

t
e
s

provid
pmml
valu
common
task

nugget

polici
episod
spot

We can also add some colour to the display. Here we make use of brewer.pal() from RColor-
Brewer (Neuwirth, 2011) to generate a palette of colours to use.

set.seed(142)
wordcloud(names(freq), freq, min.freq=100, colors=brewer.pal(6, "Dark2"))

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 29 of 40

Data Science with R

Hands-On

Text Mining

13.4 Varying the Scaling

develop
also

australian
regress

health
decis
howev
system

t
c
e

t

research

age
problem

intern

collect
particular
interv

e
d
node

australia

valu

increas
type

indic

page
advers

common
high
mean

hybrid
avail
open
csiro

object

techniqu

dataset

n
a
m
o
d

new

current
occur
transact
journal

model

predict

pattern

medic

train

signific

p
a
m
contain

spot

test
present

knowledg

group
estim

mine

rule

risk

will
interesting
sampl
follow
three
approach
classif

t
e
s
confer

data

general

build

day

result
hospit

effici
propos

s
s
a
c

unexpect

a
m
s

consist

l
l

i

similar
target
tfunction
r
o
tool
p
repres
p
explor
u
s
appli

link

year

l

subspac
variabl
user
univers

intellig
william
implement
method
base
select
effect

averag
section
well
call
error
form
work
show
like

individu

i

i

fig

l

utar

ratio

state

a

allow

polici

stage

condit

experi

l
t
t
a
r

http

t
s

task

t
s
o
c

total

refer

t
s
x
e

n
e
t
f
o

pmml

requir

report

d
n
a
t
s
r
e
d
n
u

discov

scienc

t
s
i
t

subset

d
u
t
s

observ

nugget

i
t

machin

window

compar

differ

technolog

structur

applic

chang
entiti

unit
accuraci
singl

r
e
p
o
reaction

includ
lead
attribut

databas
area
insur
acsi
tempor
tabl
make
level
drug
mani
hot
discuss
two

rank
combin
gevalu
r
a
import
random
perform
measur
distanc
e
m

describ
one

size
care
weight

episod
comput

order
angioedema

given kdd
vector

tree

provid
find

use

inform

associ

may
generat

popul
classifi
forest

d
o
i
r
e
p
network

relat
discoveri
packag

need
usual
distribut
neural
point
figur

exampl
t proceed
r
e
p
x
e

step event
search
servic
outlier

analysi
paper
patient
claim
visual
process

expect
case
adr
within
multipl
identifi
number
sequenc
defin

graham
rnn
record
learn
featur
can

interest
sourc
first
cluster
algorithm

D R A F T

consid

We can change the range of font sizes used in the plot using the scale= option. By default the
most frequent words have a scale of 4 and the least have a scale of 0.5. Here we illustrate the
e↵ect of increasing the scale range.

set.seed(142)
wordcloud(names(freq), freq, min.freq=100, scale=c(5, .1), colors=brewer.pal(6, "Dark2"))

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 30 of 40

Data Science with R

Hands-On

Text Mining

13.5 Rotating Words

t
r
e
p
x
e
http
exampl
occur
regress
pmml
valu
sampl
health
common

age

t
s
e

t

vector
entiti
sourc
australian
risk
three

nugget
present
m

i
t
s
e

techniqu

group

also
interv

predict

medic

v
o
c
s
d

i

p
i
t
l
u
m

avail

usual
mean

l

y
a
m

relat
proceed
weight
journal
observ
report

l
l

n
i
f
e
d

a
m
s
graham
classif
structur
neural

size

intern
open

object
popul
csiro
interesting
problem

p
a
m

m
h

t
i
r
o
g
a

l

scienc

confer

first
high
need

page

visual
indic
chang
singl

t
c
e
e
d

t

machin

t

dataset
network
cluster
e
task
s
system
increas
r
e
f
e
r

transact
process

insur

train
follow
approach
current
kdd

t
o
p
s

collect
tree
hybrid
use

discoveri
rule
learn
node
featur
given
hot
paper
acsi
distribut
tempor
condit
error
t
s
o
c
s
s
a
c

t
r
o
p
p
u
s

t
s
i
t

l

day

i

i

i

i

l

i

i

i

l

i

i

l

t

call

i
t

c
i
f
f
e

l
t
t
a
r

e
t
a
t
s

well

allow

a
t
s

t
r
o
p
m

one

hospit

experi

consid

search

u
d
v
d
n

n
a
m
o
d

similar

total
order

will
new

make
servic

univers
user

expect
adr

fig
d
n
a
t
s
r
e
d
n
u

howev
sequenc

inform
analysi

case
intellig
d
u

patient
identifi

stage
implement
australia

advers
can
particular

technolog
claim
type
care

t
s
d
e
o
r
e
i
r
e
n
p
two
target

outlier
variabl
function
repres

t
s
x
e
reaction
effect
base

n
e
t
f
o
build
result
accuraci
subspac
consist

discuss
william
t
s
area
combin
tool
subset
explor
step
method

number
pattern
drug
figur
ratio
record
mani
angioedema
b
appli
i
r
c
propos
s
e
e
v
databas
d
e
unexpect
rnn
general
unit
differ
requir

lead
includ
random
g
like
rank
r
section
a
year
evalu
m
averag
event
r
o
f
tabl
utar
work
perform
select
link
attribut
classifi
show
measur
distanc
e
m

D R A F T

within
provid
window
model

mine

packag
comput
research

knowledg
contain

applic
find

c
o
s
s
a

t
s
e
r
o
f

decis

compar

episod

point

polici

n
g
s

c
i
f
i

i

i

data

generat

r
e
p
o

develop

We can change the proportion of words that are rotated by 90 degrees from the default 10% to,
say, 20% using rot.per=0.2.

set.seed(142)
dark2 <- brewer.pal(6, "Dark2")
wordcloud(names(freq), freq, min.freq=100, rot.per=0.2, colors=dark2)

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 31 of 40

Data Science with R

Hands-On

Text Mining

14 Quantitative Analysis of Text

The qdap (Rinker, 2014) package provides an extensive suite of functions to support the quanti-
tative analysis of text.

We can obtain simple summaries of a list of words, and to do so we will illustrate with the
terms from our Term Document Matrix tdm. We ﬁrst extract the shorter terms from each of our
documents into one long word list. To do so we convert tdm into a matrix, extract the column
names (the terms) and retain those shorter than 20 characters.

words <- dtm
as.matrix
colnames
(function(x) x[nchar(x) < 20])

%>%
%>%
%>%

We can then summarise the word list. Notice, in particular, the use of dist tab() from qdap to
generate frequencies and percentages.

"aadrbltn"
"abbrev"
"abel"

15
34

16
28

17
22

length(words)

## [1] 6456

head(words, 15)

## [1] "aaai"
"aab"
## [6] "aadrhtmliv" "aai"
"abc"
## [11] "abbrevi"

summary(nchar(words))

##
##

Min. 1st Qu.
5.000

3.000

table(nchar(words))

Median
6.000

3

##
6
4
##
## 579 867 1044 1114
19
##
16
##

18
21

5

dist_tab(nchar(words))

"aad"
"aam"
"abcd"

"aadrbhtm"
"aba"
"abdul"

D R A F T

Max.
8.000 19.000

9
651 397

11
268 200

Mean 3rd Qu.

7
935

12
138

6.644

14
63

13
79

10

8

interval freq cum.freq percent cum.percent
8.97
579
22.40
1446
38.57
2490
55.82
3604
70.31
4539
80.39
5190
86.54
5587
90.69
5855
93.79
6055
95.93
6193

579
3
4
867
5 1044
6 1114
935
7
651
8
397
9
268
10
200
11
138
12

8.97
13.43
16.17
17.26
14.48
10.08
6.15
4.15
3.10
2.14

##
## 1
## 2
## 3
## 4
## 5
## 6
## 7
## 8
## 9
## 10
....

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 32 of 40

Data Science with R

Hands-On

Text Mining

14.1 Word Length Counts

900

s
d
r
o
W

f
o

r
e
b
m
u
N

600

300

0

A simple plot is then e↵ective in showing the distribution of the word lengths. Here we create a
single column data frame that is passed on to ggplot() to generate a histogram, with a vertical
line to show the mean length of words.

data.frame(nletters=nchar(words))

ggplot(aes(x=nletters))
geom_histogram(binwidth=1)
geom_vline(xintercept=mean(nchar(words)),

colour="green", size=1, alpha=.5)

labs(x="Number of Letters", y="Number of Words")

20

%>%
+
+

+

5

15

10

Number of Letters

D R A F T

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 33 of 40

 
 
Data Science with R

Hands-On

Text Mining

14.2 Letter Frequency

r
e
t
t
e
L

E
A
I
R
T
O
N
S
L
C
U
M
P
D
H
G
B
F
W
V
K
Y
X
Q
J
Z

0%

Next we want to review the frequency of letters across all of the words in the discourse. Some
data preparation will transform the vector of words into a list of letters, which we then construct
a frequency count for, and pass this on to be plotted.

We again use a pipeline to string together the operations on the data. Starting from the vec-
tor of words stored in word we split the words into characters using str split() from stringr
(Wickham, 2012), removing the ﬁrst string (an empty string) from each of the results (using
sapply()). Reducing the result into a simple vector, using unlist(), we then generate a data
frame recording the letter frequencies, using dist tab() from qdap. We can then plot the letter
proportions.

2%

4%

8%

10%

6%
Proportion

D R A F T

levels=toupper(interval[order(freq)])))

%>%

library(dplyr)
library(stringr)

words

str_split("")
sapply(function(x) x[-1])
unlist
dist_tab
mutate(Letter=factor(toupper(interval),

ggplot(aes(Letter, weight=percent))
geom_bar()
coord_flip()
ylab("Proportion")
scale_y_continuous(breaks=seq(0, 12, 2),

12%

%>%
%>%
%>%
%>%

%>%
+
+
+
+

label=function(x) paste0(x, "%"),
expand=c(0,0), limits=c(0,12))

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 34 of 40

Data Science with R

Hands-On

Text Mining

14.3 Letter and Position Heatmap

r
e
t
t
e
L

A

B

C

D

E

F

G

H

I

J

K

L

M

N

O

P

Q

R

S

T

U

V

W

X

Y

Z

.010 .019 .013 .010 .010 .007 .005 .003 .002 .002 .001 .001 .001 .000 .000 .000 .000 .000 .000

.006 .001 .004 .002 .002 .002 .001 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000

.013 .003 .007 .006 .004 .004 .003 .002 .001 .001 .000 .000 .000 .000 .000 .000 .000 .000 .000

.008 .002 .005 .005 .004 .003 .002 .001 .001 .001 .001 .000 .000 .000 .000 .000 .000 .000 .000

.006 .021 .010 .016 .014 .008 .005 .003 .002 .001 .001 .001 .000 .000 .000 .000 .000 .000 .000

.005 .001 .003 .002 .001 .001 .001 .001 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000

.004 .001 .004 .004 .002 .002 .002 .001 .001 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000

.005 .005 .002 .004 .003 .002 .001 .001 .001 .001 .000 .000 .000 .000 .000 .000 .000 .000 .000

.007 .015 .009 .011 .012 .009 .007 .005 .003 .002 .001 .001 .001 .000 .000 .000 .000 .000 .000

.002 .000 .001 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000

.002 .000 .001 .003 .001 .000 .001 .001 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000

Proportion

The qheat() function from qdap provides an e↵ective visualisation of tabular data. Here we
transform the list of words into a position count of each letter, and constructing a table of the
proportions that is passed on to qheat() to do the plotting.

0.000

0.005

0.010

0.015

0.020

1

2

3

4

.005 .005 .008 .008 .006 .004 .004 .002 .001 .001 .001 .001 .000 .000 .000 .000 .000 .000 .000

.009 .003 .007 .005 .003 .003 .002 .002 .001 .001 .000 .000 .000 .000 .000 .000 .000 .000 .000

.005 .010 .012 .008 .007 .009 .005 .004 .003 .002 .001 .001 .000 .000 .000 .000 .000 .000 .000

.005 .021 .009 .008 .009 .005 .005 .003 .002 .002 .001 .001 .000 .000 .000 .000 .000 .000 .000

.011 .003 .006 .005 .002 .002 .001 .001 .001 .001 .000 .000 .000 .000 .000 .000 .000 .000 .000

.001 .001 .001 .001 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000

.009 .012 .013 .009 .010 .009 .006 .004 .002 .002 .001 .001 .000 .000 .000 .000 .000 .000 .000

.015 .004 .011 .008 .007 .006 .005 .003 .002 .001 .001 .001 .000 .000 .000 .000 .000 .000 .000

.008 .005 .012 .013 .009 .008 .007 .005 .003 .002 .001 .001 .001 .000 .000 .000 .000 .000 .000

.004 .010 .005 .005 .004 .003 .002 .002 .001 .001 .000 .000 .000 .000 .000 .000 .000 .000 .000

.003 .001 .003 .002 .001 .001 .001 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000

.005 .002 .002 .001 .001 .001 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000

.001 .002 .001 .001 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000

.001 .001 .002 .001 .001 .001 .001 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000

.001 .000 .000 .001 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000 .000

19

6

8

5

7

16

13

14

12

17

18

15

10

11

9
Position

D R A F T

position=unname(x))),

\\

1, function(y) y/length(x)))

lapply(function(x) sapply(letters, gregexpr, x, fixed=TRUE))
unlist
(function(x) x[x!=-1])
(function(x) setNames(x, gsub("
(function(x) apply(table(data.frame(letter=toupper(names(x)),

d", "", names(x))))

values=TRUE, digits=3, plot=FALSE)

ylab("Letter")
xlab("Position")
theme(axis.text.x=element_text(angle=0))
guides(fill=guide_legend(title="Proportion"))

qheat(high="green", low="yellow", by.column=NULL,

words

%>%
%>%
%>%
%>%
%>%

%>%

+
+
+
+

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 35 of 40

Data Science with R

Hands-On

Text Mining

14.4 Miscellaneous Functions

We can generate gender from a name list, using the genderdata (?) package

devtools::install_github("lmullen/gender-data-pkg")

name2sex(qcv(graham, frank, leslie, james, jacqui, jack, kerry, kerrie))

## [1] M M F M F M F F
## Levels: F M

D R A F T

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 36 of 40

Data Science with R

Hands-On

Text Mining

15 Review—Preparing the Corpus

Here in one sequence is collected the code to perform a text mining project. Notice that we would
not necessarily do all of these steps so pick and choose as is appropriate to your situation.
# Required packages

library(tm)
library(wordcloud)

# Locate and load the Corpus.

cname <- file.path(".", "corpus", "txt")
docs <- Corpus(DirSource(cname))

docs
summary(docs)
inspect(docs[1])

# Transforms

toSpace <- content_transformer(function(x, pattern) gsub(pattern, " ", x))
docs <- tm_map(docs, toSpace, "/|@|

\\

|")

D R A F T

docs <- tm_map(docs, content_transformer(tolower))
docs <- tm_map(docs, removeNumbers)
docs <- tm_map(docs, removePunctuation)
docs <- tm_map(docs, removeWords, stopwords("english"))
docs <- tm_map(docs, removeWords, c("own", "stop", "words"))
docs <- tm_map(docs, stripWhitespace)

toString <- content_transformer(function(x, from, to) gsub(from, to, x))
docs <- tm_map(docs, toString, "specific transform", "ST")
docs <- tm_map(docs, toString, "other specific transform", "OST")

docs <- tm_map(docs, stemDocument)

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 37 of 40

Data Science with R

Hands-On

Text Mining

16 Review—Analysing the Corpus

# Document term matrix.

dtm <- DocumentTermMatrix(docs)
inspect(dtm[1:5, 1000:1005])

# Explore the corpus.

findFreqTerms(dtm, lowfreq=100)
findAssocs(dtm, "data", corlimit=0.6)

freq <- sort(colSums(as.matrix(dtm)), decreasing=TRUE)
wf

<- data.frame(word=names(freq), freq=freq)

library(wordcloud)
wordcloud(names(freq), freq, min.freq=100, colors=brewer.pal(6, "Dark2"))

library(ggplot2)

p <- ggplot(subset(wf, freq>500), aes(word, freq))
p <- p + geom_bar(stat="identity")
p <- p + theme(axis.text.x=element_text(angle=45, hjust=1))

# Generate a word cloud

D R A F T

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 38 of 40

Data Science with R

Hands-On

Text Mining

17 Further Reading and Acknowledgements

The Rattle Book, published by Springer, provides a comprehensive
introduction to data mining and analytics using Rattle and R.
It is available from Amazon. Other documentation on a broader
selection of R topics of relevance to the data scientist is freely
available from http://datamining.togaware.com, including the
Datamining Desktop Survival Guide.

This chapter is one of many chapters available from http://
HandsOnDataScience.com.
In particular follow the links on the
website with a * which indicates the generally more developed chap-
ters.

Other resources include:

The Journal of Statistical Software article, Text Mining Infrastructure in R is a good start
http://www.jstatsoft.org/v25/i05/paper

Bilisoly (2008) presents methods and algorithms for text mining using Perl.

Thanks also to Tony Nolan for suggestions of some of the examples used in this chapter.

Some of the qdap examples were motivated by http://trinkerrstuff.wordpress.com/2014/
10/31/exploration-of-letter-make-up-of-english-words/.

D R A F T

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 39 of 40

Data Science with R

Hands-On

Text Mining

18 References

Bilisoly R (2008). Practical Text Mining with Perl. Wiley Series on Methods and Applications
in Data Mining. Wiley. ISBN 9780470382851. URL http://books.google.com.au/books?id=
YkMFVbsrdzkC.

Bouchet-Valat M (2014). SnowballC: Snowball stemmers based on the C libstemmer UTF-8
library. R package version 0.5.1, URL http://CRAN.R-project.org/package=SnowballC.

Feinerer I, Hornik K (2014).
//CRAN.R-project.org/package=tm.

tm: Text Mining Package. R package version 0.6, URL http:

Gentry J, Long L, Gentleman R, Falcon S, Hahne F, Sarkar D, Hansen KD (2014). Rgraphviz:
Provides plotting capabilities for R graph objects. R package version 2.6.0.

Neuwirth E (2011). RColorBrewer: ColorBrewer palettes. R package version 1.0-5, URL http:
//CRAN.R-project.org/package=RColorBrewer.

R Core Team (2014). R: A Language and Environment for Statistical Computing. R Foundation
for Statistical Computing, Vienna, Austria. URL http://www.R-project.org/.

Rinker T (2014). qdap: Bridging the Gap Between Qualitative Data and Quantitative Analysis.
R package version 2.2.0, URL http://CRAN.R-project.org/package=qdap.

Wickham H (2012). stringr: Make it easier to work with strings. R package version 0.6.2, URL
http://CRAN.R-project.org/package=stringr.

Williams GJ (2009). “Rattle: A Data Mining GUI for R.” The R Journal, 1(2), 45–55. URL
http://journal.r-project.org/archive/2009-2/RJournal_2009-2_Williams.pdf.

Williams GJ (2011). Data Mining with Rattle and R: The art of excavating data for knowl-
edge discovery. Use R! Springer, New York. URL http://www.amazon.com/gp/product/
1441998896/ref=as_li_qf_sp_asin_tl?ie=UTF8&tag=togaware-20&linkCode=as2&camp=
217145&creative=399373&creativeASIN=1441998896.

D R A F T

This document, sourced from TextMiningO.Rnw revision 531, was processed by KnitR version
1.7 of 2014-10-13 and took 36.8 seconds to process. It was generated by gjw on nyx running
Ubuntu 14.04.1 LTS with Intel(R) Xeon(R) CPU W3520 @ 2.67GHz having 8 cores and 12.3GB
of RAM. It completed the processing 2014-11-05 19:22:29.

Copyright

2013-2014 Graham@togaware.com

Module: TextMiningO

Page: 40 of 40

