# Introduction

This tutorial introduces Text Analysis (see Bernard and Ryan 1998; Kabanoff 1997; Popping 2000), i.e. computer-based analysis of language data or the (semi-)automated extraction of information from text. While Text Analysis encompasses a wide range of methods, this tutorial will only serve as a very basic introduction that highlights selected, commonly used techniques. The entire code for the sections below can be downloaded here.

Since Text Analysis extracts and analyses information from language data, it can be considered a derivative of computational linguistics or an application of Natural Language Processing (NLP) to HASS research. As such, Text Analysis represents the application of computational methods in the humanities. The advantage of Text Analysis over manual or traditional techniques (close reading) lies in the fact that Text Analysis allows the extraction of information from large sets of textual data and in a replicable manner. Other terms that are more or less synonymous with Text Analysis are Text Mining, Text Analytics, and Distant Reading. In some cases, Text Analysis is considered more qualitative while Text Analytics is considered to be quantitative. This distinction is not taken up here as Text Analysis, while allowing for qualitative analysis, builds upon quantitative information, i.e. information about frequencies or conditional probabilities.

Distant Reading is a cover term for applications of Text Analysis that allow to investigate literary and cultural trends using text data. Distant Reading contrasts with close reading, i.e. reading texts in the traditional sense whereas Distant Reading refers to the analysis of large amounts of text. Text Analysis and distant reading are similar with respect to the methods that are used but different with respect to their outlook. The outlook of distant reading is to extract information from text without close reading, i.e. reading the document(s) itself but rather focusing on emerging patterns in the language that is used.

Text Analysis or Distant Reading are rapidly growing in use and gaining popularity in the humanities because textual data is readily available and because computational methods can be applied to a huge variety of research questions. The attractiveness of computational text analysis is thus based on the availability of (large amounts of) digitally available texts and in their capability to provide insights that cannot be derived from close reading techniques.

While rapidly growing as a valid approach to analysing textual data, Text Analysis is critizised for lack of "quantitative rigor and because its findings are either banal or, if interesting, not statistically robust (see here. This criticism is correct in that most of the analysis that performed in Computational Literary Studies (CLS) are not yet as rigorous as analyses in fields that have a longer history of computational based, quantitative research, such as, for instance, corpus linguistics. However, the practices and methods used in CLS will be refined, adapted and show a rapid increase in quality if more research is devoted to these approaches. Also, Text Analysis simply offers an alternative way to analyse texts that is not in competition to traditional techniques but rather complements them.

Given it relatively recent emergence, so far, most of the applications of Text Analysis are based upon a relatively limited number of key procedures or concepts (e.g. concordancing, word frequencies, annotation or tagging, parsing, collocation, text classification, Sentiment Analysis, Entity Extraction, Topic Modeling, etc.). In the following, we will explore these procedures and introduce some basic tools that help you perform the introduced tasks.

## Text Analysis at UQ

The UQ Library offers a very handy and attractive summary of resources, concepts, and tools that can be used by researchers interested in Text Analysis and Distant Reading. Also, the UQ library site offers short video introductions and addresses issues that are not discussed here such as copyright issues, data sources available at the UQ library, as well as social media and web scaping.

In contrast to the UQ library site, the focus of this introduction lies on the practical how-to of text analysis. this means that the following concentrates on how to perform analyses rather than discussing their underlying concepts or evaluating their scientific merits.

## Tools versus Scripts

It is perfectly fine to use tools for the analyses exemplified below. However, the aim here is not primarily to show how to perform text analyses but how to perform text analyses in a way that complies with practices that guarantee sustainable, transparent, reproducible research. As R code can be readily shared and optimally contains all the data extraction, processing, visualization, and analysis steps, using scripts is preferable over using (commercial) software.

In addition to being not as transparent and hindering reproduction of research, using tools can also lead to dependencies on third parties which does not arise when using open source software.

Finally, the widespread use of R particularly among data scientists, engineers, and analysts reduces the risk of software errors as a very active community corrects flawed functions typically quite rapidly.

## Preparation and session set up

This tutorial is based on R. If you have not installed R or are new to it, you will find an introduction to and more information how to use R here. For this tutorials, we need to install certain packages from an R library so that the scripts shown below are executed without errors. Before turning to the code below, please install the packages by running the code below this paragraph. If you have already installed the packages mentioned below, then you can skip ahead and ignore this section. To install the necessary packages, simply run the following code - it may take some time (between 1 and 5 minutes to install all of the packages so you do not need to worry if it takes some time).

# set options
options(stringsAsFactors = F)
# install packages
install.packages(c("DT", "knitr", "kableExtra", "quanteda",
"tidyverse", "tm", "tidytext", "wordcloud2",
"scales", "quanteda.textstats",
"quanteda.textplots", "tidyr", "cluster",
"class", "NLP", "openNLP", "openNLPdata"))

Once you have installed R and RStudio and once you have also initiated the session by executing the code shown above, you are good to go.

# 1 Concordancing

In Text Analysis, concordancing refers to the extraction of words from a given text or texts (Lindquist 2009). Commonly, concordances are displayed in the form of key-word in contexts (KWIC) where the search term is shown with some preceding and following context. Thus, such displays are referred to as key word in context concordances. A more elaborate tutorial on how to perform concordancing with R is available here.

Concordancing is helpful for seeing how the term is used in the data, for inspecting how often a given word occurs in a text or a collection of texts, for extracting examples, and it also represents a basic procedure and often the first step in more sophisticated analyses of language data.

In the following, we will use R to create KWICs displays of the term organism and the phrase natural selection using Charles Darwin’s On the origin of species by means of natural selection.

We begin by loading the quanteda package that we will use for generating the KWICs and the tidyverse package that we use to process the data. In addition, we load the data which represents the text of Charles Darwin’s On the Origin of Species. For the present tutorial, we load data that is available on the LADAL GitHUb repository. If you want to know how to load your own data, have a look at this tutorial.

# load package
library(quanteda)
library(tidyverse)
# load text
darwin <- readLines("https://slcladal.github.io/data/origindarwin.txt")
# inspect
head(darwin)
## [1] "THE ORIGIN OF SPECIES "         "BY "
## [3] "CHARLES DARWIN "                "AN HISTORICAL SKETCH "
## [5] "OF THE PROGRESS OF OPINION ON " "THE ORIGIN OF SPECIES "

The data still consists of short text snippets which is why we collapse these snippets and then split the collapsed data into chapters.

# combine and split into chapters
darwin_chapters <- darwin %>%
# paste all texts together into one long text
paste0(collapse = " ") %>%
# replace Chapter I to Chapter XVI with qwertz
stringr::str_replace_all("(CHAPTER [XVI]{1,7}\\.{0,1}) ", "qwertz\\1") %>%
# convert text to lower case
tolower() %>%
# split the long text into chapters
stringr::str_split("qwertz") %>%
# unlist the result (convert into simple vector)
unlist()
# inspect structure of resultsing data
str(darwin_chapters)
##  chr [1:16] "the origin of species  by  charles darwin  an historical sketch  of the progress of opinion on  the origin of s"| __truncated__ ...

Once we have split the data into chapters, we perform the concordancing and extract the KWICs. To create these kwics, we use the kwic function from the quanteda package. This function takes the data (x), the search pattern (pattern), and the window size as its main arguments.

To start with, we generate kwics for the term organism as shown below.

# create kwic
kwic_o <- quanteda::kwic(x = darwin_chapters, # define text(s)
# define pattern
pattern = "organism",
# define window size
window = 5) %>%
# convert into a data frame
as.data.frame() %>%
# remove superfluous columns
dplyr::select(-to, -from, -pattern)

We can also use regular expressions in our search to extract not only organism but also organisms and organic. When using a regular expression in the pattern argument, we need to specify the valuetype as regex (as shown below).

# create kwic
kwic_os <- quanteda::kwic(x = darwin_chapters,
pattern = "organi.*",
window = 5,
valuetype = "regex") %>%
# convert into a data frame
as.data.frame() %>%
# remove superfluous columns
dplyr::select(-to, -from, -pattern)

When search for expressions that represent phrase and that consists out of several elements such as natural selection, we also need to specify that we are looking for a phrase in the pattern argument.

# create kwic
kwic_ns <- quanteda::kwic(x = darwin_chapters,
pattern = phrase("natural selection"),
window = 5) %>%
# convert into a data frame
as.data.frame() %>%
# remove superfluous columns
dplyr::select(-to, -from, -pattern)

We could now continue and analyze how Darwin used the phrase natural selection or we could go about investigating how Darwin has used the term organism.

# 2 Word Frequency

Almost all methods used in text analytics rely on frequency information. Thus, fending out out frequent words are in a text is a fundamental technique in text analytics. In fact, frequency information lies at the very core of Text Analysis. Such frequency information often comes in the form of word frequency lists, i.e. lists of word forms and their frequency in a given text or collection of texts.

As extracting word frequency lists is very important, we will now We will now extract a frequency list from a corpus.

In a first step, we load a corpus, convert everything to lower case, remove non-word symbols (including punctuation), and split the corpus data into individual words.

# load package
library(tm)
# load and process corpus
darwin_words <- darwin  %>%
# convert everything to lower case
tolower() %>%
# remove non-word characters
str_replace_all("[^[:alpha:][:space:]]*", "")  %>%
tm::removePunctuation() %>%
stringr::str_squish() %>%
stringr::str_split(" ") %>%
unlist()
# inspect result
head(darwin_words, 20)
##  [1] "the"        "origin"     "of"         "species"    "by"
##  [6] "charles"    "darwin"     "an"         "historical" "sketch"
## [11] "of"         "the"        "progress"   "of"         "opinion"
## [16] "on"         "the"        "origin"     "of"         "species"

Now that we have a vector of words, we can easily create a table representing a word frequency list (as shown below).

# create table
wfreq <- darwin_words %>%
table() %>%
as.data.frame() %>%
arrange(desc(Freq)) %>%
dplyr::rename(word = 1,
frequency = 2)

The most frequent words are all function words which are often not meaningful or useful for an analysis. Thus, we now remove these function words (also called stopwords) from the frequency list and inspect the list without stopwords.

# load package
library(tidytext)
# create table wo stopwords
wfreq_wostop <- wfreq %>%
anti_join(stop_words, by = "word") %>%
dplyr::filter(word != "")
Words and their (relative) freqeuncy in Darwin’s Origin
word frequency
species 1755
forms 524
natural 513
selection 505
varieties 409
plants 396
animals 362
life 330
distinct 326
nature 301

Such word frequency lists can be visualized in various ways. The most common way to visualize word frequency lists is in the form of bargraphs.

wfreq_wostop %>%
head(10) %>%
ggplot(aes(x = reorder(word, -frequency, mean), y = frequency)) +
geom_bar(stat = "identity") +
labs(title = "10 most frequent non-stop words in \nCharles Darwin's *Origin of Species*",
x = "") +
theme(axis.text.x = element_text(angle = 45, size = 12, hjust = 1))

## Wordclouds

Alternatively, word frequency lists can be visualized, although less informative, as word clouds.

# load packages
library(wordcloud2)
library(scales)
# create wordcloud
wordcloud2(wfreq_wostop[1:100,],
shape = "diamond",
color = scales::viridis_pal()(8)
)

Another variant of word clouds, so-called comparison clouds, Word lists can be used to determine differences between texts. For instance, we can load different texts and check whether they differ with respect to word frequencies. To show this, we load Herman Melville’s Moby Dick, George Orwell’s 1984, and we also use Darwin’s Origin.

In a first step, we load these texts and collapse them into single documents.

# load data
orwell <- readLines("https://slcladal.github.io/data/orwell.txt") %>%
paste0(collapse = " ")
melville <- readLines("https://slcladal.github.io/data/melvillemobydick.txt") %>%
paste0(collapse = " ")
darwin_doc <- paste0(darwin, collapse = " ")

Now, we generate a corpus object from these texts and create a variable with the author name.

corp_dom <- quanteda::corpus(c(darwin_doc, orwell, melville))
attr(corp_dom, "docvars")$Author = c("Darwin", "Orwell", "Melville") Now, we can remove stopwords and punctuation and generate the comparison cloud. corp_dom %>% tokens(remove_punct = TRUE) %>% tokens_remove(stopwords("english")) %>% dfm() %>% dfm_group(groups = corp_dom$Author) %>%
dfm_trim(min_termfreq = 200, verbose = FALSE) %>%
textplot_wordcloud(comparison = TRUE, max_words = 100,
min_size= 1, max_size = 6)

## Frequency changes

We can also investigate the use of the term organism across chapters in Darwin’s Origin. In a first step, we extract the number of words in each chapter.

# extract number of words per chapter
Words <- darwin_chapters %>%
stringr::str_split(" ")  %>%
lengths()
# inspect data
Words
##  [1]  1856 14065  7456  7136 22317 13916 17781 19055 15847 14741 13313 12996
## [13] 13753  9817 20967 12987

Next, we extract the number of matches in each chapter.

# extract number of matches per chapter
Matches <- darwin_chapters %>%
stringr::str_count("organism[s]{0,1}")
# inspect the number of matches per chapter
Matches
##  [1]  0  5  3  3  9  3  3  3  0  1  6  6 10  5  8  7

Now, we extract the names of the chapters and create a table with the chapter names and the relative frequency of matches per 1,000 words.

# extract chapters
Chapters <- darwin_chapters %>%
stringr::str_replace_all("(chapter [xvi]{1,7})\\.{0,1} .*", "\\1")
Chapters <- dplyr::case_when(nchar(Chapters) > 50 ~ "chapter 0", TRUE ~ Chapters)
Chapters
##  [1] "chapter 0"    "chapter i"    "chapter ii"   "chapter iii"  "chapter iv"
##  [6] "chapter v"    "chapter vi"   "chapter vii"  "chapter viii" "chapter ix"
## [11] "chapter x"    "chapter xi"   "chapter xii"  "chapter xiii" "chapter xiv"
## [16] "chapter xv"
# create table of results
tb <- data.frame(Chapters, Matches, Words) %>%
dplyr::mutate(Frequency = round(Matches/Words*1000, 2))
Words and their (relative) freqeuncy across chapters in Darwin’s Origin
Chapters Matches Words Frequency
chapter 0 0 1856 0.00
chapter i 5 14065 0.36
chapter ii 3 7456 0.40
chapter iii 3 7136 0.42
chapter iv 9 22317 0.40
chapter v 3 13916 0.22
chapter vi 3 17781 0.17
chapter vii 3 19055 0.16
chapter viii 0 15847 0.00
chapter ix 1 14741 0.07

We can now visualize the relative frequencies of our search word per chapter.

# create plot
ggplot(tb, aes(x = Chapters, y = Frequency, group = 1)) +
geom_smooth(color = "goldenrod2") +
geom_line(color = "indianred4") +
guides(color=guide_legend(override.aes=list(fill=NA))) +
theme_bw() +
theme(axis.text.x = element_text(angle = 45, hjust = 1))+
scale_y_continuous(name ="Relative Frequency (per 1,000 words)")

## Dispersion plots

To show when in a text or in a collection of texts certain terms occur, we can use dispersion plots. The quanteda package offers a very easy-to-use function textplot_xray to generate dispersion plots.

# add chapter names
names(darwin_chapters) <- Chapters
# generate corpus from chapters
darwin_corpus <- quanteda::corpus(darwin_chapters)
# generate dispersion plots
textplot_xray(kwic(darwin_corpus, pattern = "organism"),
kwic(darwin_corpus, pattern = "selection"),
sort = T)

## Over- and underuse

Frequency information can also tell us something about the nature of a text. For instance, private dialogues will typically contain higher rates of second person pronouns compared with more format text types, such as, for instance, scripted monologues like speeches. For this reason, word frequency lists can be used in text classification and to determine the formality of texts.

As an example, below you find the number of the second person pronouns you and your and the number of all words except for these second person pronouns in private dialogues compared with scripted monologues in the Irish component of the International Corpus of English (ICE). In addition, the tables shows the percentage of second person pronouns in both text types to enable seeing whether private dialogues contain more of these second person pronouns than scripted monologues (i.e. speeches).

Use of 2nd person pronouns (and all other words) in ICE Ireland
Private dialogues Scripted monologues
you, your 6761 659
Other words 259625 105295
Percent 2.60 0.63

This simple example shows that second person pronouns make up 2.6 percent of all words that are used in private dialogues while they only amount to 0.63 percent in scripted speeches. A handy way to present such differences visually are association and mosaic plots.

d <- matrix(c(6761, 659, 259625, 105295), nrow = 2, byrow = T)
colnames(d) <- c("D", "M")
rownames(d) <- c("you, your", "Other words")
assocplot(d)

Bars above the dashed line indicate relative overuse while bars below the line suggest relative under-use. Therefore, the association plot indicates under-use of you and your and overuse of other words in monologues while the opposite trends holds true for dialogues, i.e. overuse of you and your and under-use of Other words.

# 3 N-grams, Collocations, and Keyness

Collocation refers to the co-occurrence of words. A typical example of a collocation is Merry Christmas because the words merry and Christmas occur together more frequently together than would be expected by chance, if words were just randomly stringed together.

N-grams are related to collocates in that they represent words that occur together (bi-grams are two words that occur together, tri-grams three words and so on). Fortunately, creating N-gram lists is very easy. We will use the Origin to create a bi-gram list. We can simply take each word and combine it with the following word.

# create data frame
darwin_bigrams <- data.frame(darwin_words[1:length(darwin_words)-1],
darwin_words[2:length(darwin_words)]) %>%
dplyr::rename(Word1 = 1,
Word2 = 2) %>%
dplyr::mutate(Bigram = paste0(Word1, " ", Word2)) %>%
dplyr::group_by(Bigram) %>%
dplyr::summarise(Frequency = n()) %>%
dplyr::arrange(-Frequency)
Bigrams and their (relative) freqeuncy in Darwin’s Origin
Bigram Frequency
of the 2673
in the 1440
the same 959
to the 791
on the 744
have been 624
that the 574
it is 500
natural selection 367
and the 351

Both N-grams and collocations are not only an important concept in language teaching but they are also fundamental in Text Analysis and many other research areas working with language data. Unfortunately, words that collocate do not have to be immediately adjacent but can also encompass several slots which makes it harder to retrieve of collocates that are not adjacent- We will find out how to identify non-adjacent collocates in the next section.

## Finding collocations

There are various techniques for identifying collocations. To identify collocations without having a pre-defined target term, we can use the textstat_collocations function from the quanteda.textstats package.

However, before we can apply that function and start identifying collocations, we need to process teh data to which we want to apply this fucntion. In the present case, we will apply that function to the sentences in Charles darwin’s Origin which we extract in the code chunk below.

darwin_sentences <- darwin %>%
tolower() %>%
paste0(collapse= " ") %>%
stringr::str_split(fixed(".")) %>%
unlist() %>%
tm::removePunctuation() %>%
stringr::str_squish()
First 10 sentences in Darwin’s Origin
x
the origin of species by charles darwin an historical sketch of the progress of opinion on the origin of species introduction when on board h
m
s
beagle as naturalist i was much struck with certain facts in the distribution of the organic beings in habiting south america and in the geological relations of the present to the past inhabitants of that continent
these facts as will be seen in the latter chapters of this volume seemed to throw some light on the origin of species — that mystery of mysteries as it has been called by one of our greatest philosophers
on my return home it occurred to me in 1837 that something might perhaps be made out on this question by patiently accumulating and reflecting on all sorts of facts which could possibly have any bearing on it
after five years work i allowed myself to specu late on the subject and drew up some short notes these i enlarged in 1844 into a sketch of the conclusions which then seemed to me probable from that period to the present day i have steadily pursued the same object
i hope that i may be excused for entering on these personal details as i give them to show that i have not been hasty in coming to a decision
my work is now 1859 nearly finished but as it will take me many more years to complete it and as my health is far from strong i have been urged to publish this abstract
i have more especially been induced to do this as mr

From the output shown above, we also see that splitting texts simply by full stops is not optimal as it produces some unwarranted artefacts like the “sentences” that consist of single characters (due to the name of the H.M.S. Beagle - the ship on which Darwin traveled when he explored the southern hemisphere). Fortunately, these errors do not really matter in the case of our example.

Now that we have split Darwin’s Origin into sentences, we can tokenize these sentences and apply the textstat_collocations function which identifies collocations.

# load packages
library(quanteda.textstats)
# create a token object
darwin_tokens <- tokens(darwin_sentences, remove_punct = TRUE) %>%
tokens_remove(stopwords("english"))
# extract collocations
darwin_coll <- textstat_collocations(darwin_tokens, size = 2, min_count = 20)
Collocations in Charles darwin’s Origin
collocation count count_nested length lambda z
natural selection 367 0 2 7.442662 57.36943
conditions life 107 0 2 5.807671 39.91801
organic beings 105 0 2 8.179323 37.34842
closely allied 64 0 2 6.561562 33.85212
south america 41 0 2 7.415450 28.81440
widely different 49 0 2 5.317774 28.29759
modified descendants 40 0 2 6.092974 27.68700
state nature 45 0 2 5.331289 27.38031
theory natural 54 0 2 4.864304 27.35902
distinct species 102 0 2 3.307347 26.97796
north america 31 0 2 7.091204 26.01263
forms life 57 0 2 3.844558 25.11312
struggle existence 27 0 2 6.889213 25.08157
individual differences 30 0 2 5.922674 24.97534
united states 29 0 2 8.330146 24.94125

The resulting table shows collocations in Darwin’s Origin decending by collocation strength.

## Visualizing Collocation Networks

Network graphs are a very useful and flexible tool for visualizing relationships between elements such as words, personas, or authors. This section shows how to generate a network graph for collocations of the term organism using the quanteda package.

In a first step, we generate a document-feature matrix based on the sentence sin Charles Darwin’s Origin. A document-feature matrix shows how often elements (here these elements are the words that occur in the Origin) occur in a selection of documents (here these documents are the sentences in the Origin).

# create document-feature matrix
darwin_dfm <- darwin_sentences %>%
quanteda::dfm(remove = stopwords('english'), remove_punct = TRUE) %>%
quanteda::dfm_trim(min_termfreq = 10, verbose = FALSE)
First lines of the document-feature matrix.
doc_id origin species charles progress opinion h
text1 2 2 1 1 1 1
text2 0 0 0 0 0 0
text3 0 0 0 0 0 0
text4 0 0 0 0 0 0
text5 1 1 0 0 0 0
text6 0 0 0 0 0 0

As we want to generate a network graph of words that collocate with the term organism, we use the calculateCoocStatistics function to determine which words most strongly collocate with our target term (organism).

# load function for co-occurrence calculation
source("https://slcladal.github.io/rscripts/calculateCoocStatistics.R")
# define term
coocTerm <- "organism"
# calculate co-occurrence statistics
coocs <- calculateCoocStatistics(coocTerm, darwin_dfm, measure="LOGLIK")
# inspect results
coocs[1:20]
##  conditions      nature    relation   relations    physical      action
##   56.666499   34.485146   25.478537   22.836815   21.740633   20.608922
##        life     bearing   important        many      direct   colonists
##   18.807464   16.246065   15.812686   13.488588   12.705077   11.300306
## competition      nearly     welfare     require     altered   different
##   11.140540   10.945131   10.886868   10.514045   10.174698    9.774481
## improvement     rapidly
##    9.576033    9.576033

We now reduce the document-feature matrix to contain only the top 20 collocates of organism (plus our target word organism).

redux_dfm <- dfm_select(darwin_dfm,
pattern = c(names(coocs)[1:20], "organism"))
First lines of the reduced feature co-occurrence matrix.
doc_id relations bearing nearly many conditions important
text1 0 0 0 0 0 0
text2 0 0 0 0 0 0
text3 0 0 0 0 0 0
text4 1 0 0 0 0 0
text5 0 0 0 0 0 0
text6 0 1 0 0 0 0

Now, we can transform the document-feature matrix into a feature-co-occurrence matrix as shown below. A feature-co-occurrence matrix shows how often each element in that matrix co-occurs with every other element in that matrix.

tag_fcm <- fcm(redux_dfm)
Overview of the feature co-occurrence matrix.
doc_id relations bearing nearly many conditions important
relations 3 2 2 6 11 6
bearing 0 1 1 3 2 1
nearly 0 0 7 23 29 7
many 0 0 0 51 34 27
conditions 0 0 0 0 27 18
important 0 0 0 0 0 9

Using the feature-co-occurrence matrix, we can generate the network graph which shows the terms that collocate with the target term organism with the edges representing the co-occurrence frequency. To generate this network graph, we use the textplot_network function from the quanteda.textplots package.

# load package
library(quanteda.textplots)
# generate network graph
textplot_network(tag_fcm,
min_freq = 1,
edge_alpha = 0.1,
edge_size = 5,
edge_color = "purple",
vertex_labelsize = log(rowSums(tag_fcm))*2)

## Keyness

Another common method that can be used for automated text summarization is keyword extraction. Keyword extraction builds on identifying words that are particularly associated with a certain text. In other words, keyness analysis aims to identify words that are particularly indicative of the content of a certain text.

Below, we identify key words for Charles Darwin’s Origin, Herman Melville’s Moby Dick, and George Orwell’s 1984. We start by creating a weighted document feature matrix from the corpus containing the three texts.

dfm_authors <- corp_dom %>%
quanteda::tokens(remove_punct = TRUE) %>%
quanteda::tokens_remove(stopwords("english")) %>%
quanteda::dfm() %>%
quanteda::dfm_weight(scheme = "prop")

In a next step, we use the textstat_frequency function from the quanteda package to extract the most frequent non-stopwords in the three texts.

# Calculate relative frequency by president
freq_weight <- quanteda::textstat_frequency(dfm_authors, n = 10,
groups = dfm_authors$Author) Most common words in three texts. feature frequency rank docfreq group species 0.0175087 1 1 Darwin one 0.0077517 2 1 Darwin will 0.0075522 3 1 Darwin may 0.0064847 4 1 Darwin many 0.0058662 5 1 Darwin can 0.0057564 6 1 Darwin forms 0.0052277 7 1 Darwin natural 0.0050780 8 1 Darwin selection 0.0050381 9 1 Darwin two 0.0043896 10 1 Darwin Now, we can simply plot the most common words and most indicative non-stop words in the three texts. ggplot(freq_weight, aes(nrow(freq_weight):1, frequency)) + geom_point() + facet_wrap(~ group, scales = "free") + coord_flip() + scale_x_continuous(breaks = nrow(freq_weight):1, labels = freq_weight$feature) +
labs(x = NULL, y = "Relative frequency")

# 4 Text Classification

Text classification refers to methods that allow to classify a given text to a predefined set of languages, genres, authors, or the like. Such classifications are typically based on the relative frequency of word classes, key words, phonemes, or other linguistic features such as average sentence length, words per line, etc.

As with most other methods that are used in text analysis, text classification typically builds upon a training set that is already annotated with the required tags. Training sets and the features that are derived from these training sets can be created by oneself or one can use build in training sets that are provided in the respective software packages or tools.

In the following, we will use the frequency of phonemes to classify a text. In a first step, we read in a German text, and split it into phonemes.

# read in German text
German <- readLines("https://slcladal.github.io/data/phonemictext1.txt") %>%
stringr::str_remove_all(" ") %>%
stringr::str_split("") %>%
unlist()
# inspect data
head(German, 20)
##  [1] "?" "a" "l" "s" "h" "E" "s" "@" "d" "e" ":" "n" "S" "t" "E" "p" "@" "n" "v"
## [20] "O"

We now do the same for three other texts - an English and a Spanish text as well as one text in a language that we will determine using classification.

# read in texts
English <- readLines("https://slcladal.github.io/data/phonemictext2.txt")
Spanish <- readLines("https://slcladal.github.io/data/phonemictext3.txt")
Unknown <- readLines("https://slcladal.github.io/data/phonemictext4.txt")
# clean, split texts into phonemes, unlist and convert them into vectors
English <- as.vector(unlist(strsplit(gsub(" ", "", English), "")))
Spanish <- as.vector(unlist(strsplit(gsub(" ", "", Spanish), "")))
Unknown <- as.vector(unlist(strsplit(gsub(" ", "", Unknown), "")))
# inspect data
head(English, 20)
##  [1] "D"  "@"  "b"  "U"  "k"  "I"  "z"  "p"  "r"  "\\" "@"  "z"  "E"  "n"  "t"
## [16] "@"  "d"  "{"  "z"  "@"

We will now create a table that represents the phonemes and their frequencies in each of the 4 texts. In addition, we will add the language and simply the column names.

# create data tables
German <- data.frame(names(table(German)), as.vector(table(German)))
English <- data.frame(names(table(English)), as.vector(table(English)))
Spanish <- data.frame(names(table(Spanish)), as.vector(table(Spanish)))
Unknown <- data.frame(names(table(Unknown)), as.vector(table(Unknown)))
# add column with language
German$Language <- "German" English$Language <- "English"
Spanish$Language <- "Spanish" Unknown$Language <- "Unknown"
# simplify column names
colnames(German)[1:2] <- c("Phoneme", "Frequency")
colnames(English)[1:2] <- c("Phoneme", "Frequency")
colnames(Spanish)[1:2] <- c("Phoneme", "Frequency")
colnames(Unknown)[1:2] <- c("Phoneme", "Frequency")
# combine all tables into a single table
classdata <- rbind(German, English, Spanish, Unknown) 
First 10 lines of the class data.
Phoneme Frequency Language
6 German
: 569 German
? 556 German
@ 565 German
¼ 6 German
2 6 German
3 31 German
4 67 German
5 1 German
6 402 German

Now, we group the data so that we see, how often each phoneme is used in each language.

# activate package
library(tidyr)
# convert into wide format
classdw <- classdata %>%
spread(Phoneme, Frequency) %>%
replace(is.na(.), 0)
Overview of the class data in wide format.
Language
: ? @
English 7 8 176 0 309
German 0 6 569 556 565
Spanish 0 5 0 0 0
Unknown 12 12 286 0 468

Now, we need to transform the data again, so that we have the frequency of each phoneme by language as the classifier will use “Language” as the dependent variable and the phoneme frequencies as predictors.

numvar <- colnames(classdw)[2:length(colnames(classdw))]
classdw[numvar] <- lapply(classdw[numvar], as.numeric)
# function for normalizing numeric variables
normalize <- function(x) { (x-min(x))/(max(x)-min(x))   }
# apply normalization
classdw[numvar] <- as.data.frame(lapply(classdw[numvar], normalize))
Overview of the probabilities.
Language
: ? @
English 0.5833333 0.4285714 0.3093146 0 0.5469027
German 0.0000000 0.1428571 1.0000000 1 1.0000000
Spanish 0.0000000 0.0000000 0.0000000 0 0.0000000
Unknown 1.0000000 1.0000000 0.5026362 0 0.8283186

Before turning to the actual classification, we will use a cluster analysis to see which texts the unknown text is most similar with.

# remove language column
textm <- classdw[,2:ncol(classdw)]
# add languages as row names
rownames(textm) <- classdw[,1]
# create distance matrix
distmtx <- dist(textm)
# load package
library(cluster)
# perform clustering
clustertexts <- hclust(distmtx, method="ward.D")
# visualize cluster result
plot(clustertexts, hang = .25,main = "")           

According to the cluster analysis, the unknown text clusters together with the English texts which suggests that the unknown text is likely to be English.

Before we begin with the actual classification, we will split the data so that we have one data set without “Unknown” (this is our training set) and one data set with only “Unknown” (this is our test set).

# create training set
train <- classdw %>%
filter(Language != "Unknown")
# create test set
test <- classdw %>%
filter(Language == "Unknown")
Overview of the training set probabilities.
Language
: ? @
English 0.5833333 0.4285714 0.3093146 0 0.5469027
German 0.0000000 0.1428571 1.0000000 1 1.0000000
Spanish 0.0000000 0.0000000 0.0000000 0 0.0000000
Unknown 1.0000000 1.0000000 0.5026362 0 0.8283186

Finally, we can apply our classifier to our data. The classifier we use is a k-nearest neighbor classifier as the underlying function will classify an unknown element given its proximity to the clusters in the training set.

# load package
library(class)
# set seed for reproducibility
set.seed(12345)
# apply k-nearest-neighbor (knn) classifier
prediction <- class::knn(train[,2:ncol(train)],
test[,2:ncol(test)],
cl = train[, 1],
k = 3)
# inspect the result
prediction
## [1] English
## Levels: English German Spanish

Based on the frequencies of phonemes in the unknown text, the knn-classifier predicts that the unknown text is English. This is in fact true as the text is a subsection of the Wikipedia article for Aldous Huxley’s Brave New World. The training texts were German, English, and Spanish translations of a subsection of Wikipedia’s article for Hermann Hesse’s Steppenwolf.

# 5 Entity Extraction

Entity Extraction is a process during which textual elements which have characteristics that are common to proper nouns (locations, people, organizations, etc.) rather than other parts of speech, e.g. non-sentence initial capitalization, are extracted from texts. Retrieving entities is common in automated summarization and in Topic Modelling. Entity extraction can be achieved by simple feature extraction (e.g. extract all non-sentence initial capitalized words) or with the help of training sets. Using training sets, i.e. texts that are annotated for entities and non-entities, achieves better results when dealing with unknown data and data with inconsistent capitalization.

# load packages
library(NLP)
library(openNLP)
library(openNLPdata)
# process data
orwell <- orwell %>%
stringr::str_remove_all("Part 2,.*")
# convert text into string
orwell = as.String(orwell)
# define annotators
# sentence annotator
sent_annot = Maxent_Sent_Token_Annotator()
# word annotator
word_annot = Maxent_Word_Token_Annotator()
# location annotator
loc_annot = Maxent_Entity_Annotator(kind = "location")
# person annotator
people_annot = Maxent_Entity_Annotator(kind = "person")
# apply annotations
orwellanno = NLP::annotate(orwell, list(sent_annot, word_annot,
loc_annot, people_annot))
# extract features
k <- sapply(orwellanno\$features, [[, "kind")
# extract locations
orwelllocations = names(table(orwell[orwellanno[k == "location"]]))
# extract people
orwellpeople = names(table(orwell[orwellanno[k == "person"]]))
# inspect extract people
orwellpeople
##  [1] "Adam"                "Ah"                  "Big Brother"
##  [4] "Byron"               "Comrade Ogilvy"      "Floating Fortresses"
##  [7] "Goldstein"           "Ingsoc."             "Jews"
## [10] "Jones"               "Julius Caesar"       "Martin"
## [13] "Milton"              "Parsons"             "Peace"
## [16] "Rutherford"          "Saint Sebastian"     "Shakespeare"
## [19] "Smith"               "St Martin"           "Syme"
## [22] "Tom"                 "Winston"             "Winston Smith"
## [25] "Withers"

# Citation & Session Info

Schweinberger, Martin. 2021. Text Analysis and Distant Reading using R. Brisbane: The University of Queensland. url: https://slcladal.github.io/textanalysis.html (Version 2021.09.05).

@manual{schweinberger2021ta,
author = {Schweinberger, Martin},
title = {Text Analysis and Distant Reading using R},
note = {https://slcladal.github.io/textanalysis.html},
year = {2021},
organization = "The University of Queensland, Australia. School of Languages and Cultures},
address = {Brisbane},
edition = {2021.09.05}
}
sessionInfo()
## R version 4.0.3 (2020-10-10)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 19043)
##
## Matrix products: default
##
## locale:
## [1] LC_COLLATE=German_Germany.1252  LC_CTYPE=German_Germany.1252
## [3] LC_MONETARY=German_Germany.1252 LC_NUMERIC=C
## [5] LC_TIME=German_Germany.1252
##
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base
##
## other attached packages:
##  [1] openNLPdata_1.5.3-4     openNLP_0.2-7           class_7.3-17
##  [4] cluster_2.1.0           quanteda.textplots_0.93 slam_0.1-47
##  [7] Matrix_1.2-18           quanteda.textstats_0.93 scales_1.1.1
## [10] wordcloud2_0.2.1        tidytext_0.2.6          tm_0.7-7
## [13] NLP_0.2-1               forcats_0.5.0           stringr_1.4.0
## [16] dplyr_1.0.2             purrr_0.3.4             readr_1.4.0
## [19] tidyr_1.1.2             tibble_3.0.4            ggplot2_3.3.3
## [22] tidyverse_1.3.0         quanteda_2.1.2          kableExtra_1.3.1
## [25] knitr_1.30              DT_0.16
##
## loaded via a namespace (and not attached):
##  [1] nlme_3.1-149         fs_1.5.0             usethis_1.6.3
##  [4] lubridate_1.7.9      webshot_0.5.2        RColorBrewer_1.1-2
##  [7] httr_1.4.2           SnowballC_0.7.0      tools_4.0.3
## [10] backports_1.1.10     R6_2.5.0             DBI_1.1.0
## [13] mgcv_1.8-33          colorspace_1.4-1     withr_2.3.0
## [16] tidyselect_1.1.0     compiler_4.0.3       cli_2.1.0
## [19] rvest_0.3.6          network_1.16.1       xml2_1.3.2
## [22] labeling_0.4.2       digest_0.6.27        rmarkdown_2.5
## [25] pkgconfig_2.0.3      htmltools_0.5.0      dbplyr_2.0.0
## [28] highr_0.8            htmlwidgets_1.5.3    rlang_0.4.8
## [31] readxl_1.3.1         rstudioapi_0.11      generics_0.1.0
## [34] farver_2.0.3         jsonlite_1.7.1       statnet.common_4.4.1
## [37] crosstalk_1.1.0.1    tokenizers_0.2.1     magrittr_1.5
## [40] Rcpp_1.0.5           munsell_0.5.0        fansi_0.4.1
## [43] lifecycle_0.2.0      stringi_1.5.3        yaml_2.2.1
## [46] grid_4.0.3           ggrepel_0.8.2        parallel_4.0.3
## [49] crayon_1.3.4         lattice_0.20-41      haven_2.3.1
## [52] splines_4.0.3        hms_0.5.3            sna_2.6
## [55] pillar_1.4.6         stopwords_2.0        rle_0.9.2
## [58] fastmatch_1.1-0      reprex_0.3.0         glue_1.4.2
## [61] evaluate_0.14        data.table_1.13.2    RcppParallel_5.0.2
## [64] modelr_0.1.8         vctrs_0.3.4          cellranger_1.1.0
## [67] gtable_0.3.0         assertthat_0.2.1     xfun_0.19
## [70] broom_0.7.2          coda_0.19-4          janeaustenr_0.1.5
## [73] viridisLite_0.3.0    nsyllable_1.0        rJava_0.9-13
## [76] ellipsis_0.3.1

Back to top

Back to HOME

# References

Bernard, H Russell, and Gery Ryan. 1998. “Text Analysis.” Handbook of Methods in Cultural Anthropology 613.

Kabanoff, Boris. 1997. “Introduction: Computers Can Read as Well as Count: Computer-Aided Text Analysis in Organizational Research.” Journal of Organizational Behavior, 507–11.

Lindquist, Hans. 2009. Corpus Linguistics and the Description of English. Edinburgh: Edinburgh University Press.

Popping, Roel. 2000. Computer-Assisted Text Analysis. Sage.