-
Notifications
You must be signed in to change notification settings - Fork 189
/
Copy pathdigital-humanities.Rmd
541 lines (406 loc) · 21 KB
/
digital-humanities.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
---
title: "Replication: Text Analysis with R for Students of Literature"
author: Kenneth Benoit, Stefan Müller, and Paul Nulty
output:
html_document:
toc: true
---
In this vignette we show how the **quanteda** package can be used to replicate the analysis from Matthew Jockers' book [*Text Analysis with R for Students of Literature*](http://doi.org/10.1007/978-3-319-03164-4) (London: Springer, 2014). Most of the Jockers book consists of loading, transforming, and analyzing quantities derived from text and data from text. Because **quanteda** has built in most of the code to perform these data transformations and analyses, it makes it possible to replicate the results from the book with far less code. Throughout this vignette, we name objects based on Jockers' book, but follow the **quanteda** [style guide](https://github.com/quanetda/quanteda/wiki/Style-guide).
In what follows, each section corresponds to the respective chapter in the book.
# 1 R Basics
Our closest equivalent is simply:
```{r eval=FALSE}
install.packages("quanteda")
install.packages("readtext")
```
But if you are reading this vignette, than chances are that you have already completed this step.
# 2 First Foray
## 2.1 Loading the first text file
```{r message=FALSE}
library("quanteda")
```
We can load the text from _Moby Dick_ using the **readtext** package, directly from the [Project Gutenberg website](https://www.gutenberg.org/ebooks/2701).
```{r, eval=FALSE}
data_char_mobydick <- as.character(readtext::readtext("http://www.gutenberg.org/cache/epub/2701/pg2701.txt"))
names(data_char_mobydick) <- "Moby Dick"
```
```{r, eval=TRUE, echo=FALSE}
load("data_char_mobydick.rda")
quanteda_options(threads = 1)
RcppParallel::setThreadOptions(numThreads = 1)
```
The `readtext()` function from the **readtext** package loads the text files into a `data.frame` object. We can access the text from a `data.frame` object (and also, as we will see, a `corpus` class object). Here we will display just the first 75 characters, to prevent a massive dump of the text of the entire novel. We do this using the `stri_sub()` function from the **stringi** package, which shows the 1st through the 75th characters of the texts of our new object `data_char_mobydick`. Because we have not assigned the return from this command to any object, it invokes a print method for character objects, and is displayed on the screen.
```{r}
library("stringi")
stri_sub(data_char_mobydick, 1, 75)
```
## 2.2 Separate content from metadata
The Gutenburg edition of the text contains some metadata before and after the text of the novel. The code below uses the `regexec` and `substring` functions to separate this from the text.
```{r}
# extract the header information
(start_v <- stri_locate_first_fixed(data_char_mobydick, "CHAPTER 1. Loomings.")[1])
(end_v <- stri_locate_last_fixed(data_char_mobydick, "orphan.")[1])
```
Here, we found the character index of the beginning and end of the novel, rather than counting the lines as in the book, but the result will be very similar. If we want to verify that "orphan." is the end of the novel, we can use the `kwic()` function:
```{r out.width="\\textwidth"}
# verify that "orphan" is the end of the novel
kwic(tokens(data_char_mobydick), "orphan")
```
If we want to count the number of lines, we can do so by counting the newlines in the text.
```{r}
stri_count_fixed(data_char_mobydick, "\n")
```
To measure just the number lines in the novel itself, without the metadata, we can subset the text from the start and end of the novel part, as identified above.
```{r}
stri_sub(data_char_mobydick, from = start_v, to = end_v) |>
stri_count_fixed("\n")
```
To trim the non-book content, we use `stri_sub()` to extract the text between the beginning and ending indexes found above:
```{r}
novel_v <- stri_sub(data_char_mobydick, start_v, end_v)
length(novel_v)
stri_sub(novel_v, 1, 94) |> cat()
```
## 2.3 Reprocessing the content
We begin processing the text by converting to lower case. **quanteda**'s `*_tolower()` functions work like the built-in `tolower()`, with an extra option to preserve upper-case acronyms when detected. To work with the novel efficiently, however, we will first tokenise it. Then, we can manipulate it using functions such as `tokens_tolower()`.
```{r}
novel_v_toks <- tokens(novel_v)
# lowercase text
novel_v_toks_lower <- tokens_tolower(novel_v_toks)
```
**quanteda**'s `tokens()` function splits the text into words, with many options available for which characters should be preserved, and which should be used to define word boundaries. The default behaviour works similarly to splitting on the regular expression for non-word characters (`\W` as in the book), but it much smarter. For instance, it does not treat apostrophes as word boundaries, meaning that `'s` and `'t` are not treated as whole words from possessive forms and contractions.
To remove punctuation, we can re-process the existing tokens:
```{r}
moby_word_v <- tokens(novel_v_toks_lower, remove_punct = TRUE)
(total_length <- ntoken(moby_word_v))
moby_word_v[["text1"]][1:10]
moby_word_v[["text1"]][99986]
moby_word_v[["text1"]][c(4, 5, 6)]
# check positions of "whale"
which(moby_word_v[["text1"]] == "whale") |>
head()
```
## 2.4 Beginning the analysis
The code below uses the tokenized text to the occurrence of the word *whale*. To include the possessive form *whale's*, we may sum the counts of both forms, count the keyword-in-context matches by regular expression or glob. A *glob* is a simple wildcard matching pattern common on Unix systems -- asterisks match zero or more characters.
Note that the counts below do not match those in the book, due to differences in how the book has split on any non-word character, while **quanteda**'s tokenizer splits on a more comprehensive set of "word boundaries". **quanteda**'s `tokens()` function by default does not remove punctuation or numbers (both defined as "non-word" characters) by default. To more closely match the counts in the book, we have removed punctuation.
```{r}
lengths(tokens_select(moby_word_v, "whale"))
# total occurrences of "whale" including possessive
lengths(tokens_select(moby_word_v, c("whale", "whale's")))
# same thing using kwic()
nrow(kwic(novel_v_toks_lower, pattern = "whale"))
nrow(kwic(novel_v_toks_lower, pattern = "whale*")) # includes words like "whalemen"
(total_whale_hits <- nrow(kwic(novel_v_toks_lower, pattern = "^whale('s){0,1}$", valuetype = "regex")))
```
What fraction of the total words (excluding punctuation) in the novel are "whale"?
```{r}
total_whale_hits / ntoken(novel_v_toks_lower, remove_punct = TRUE)
```
With `ntype()` we can calculate the size of the vocabulary -- includes possessive forms, but excludes punctuation, symbols and numbers.
```{r}
# total unique words
length(unique(moby_word_v))
ntype(novel_v_toks_lower, remove_punct = TRUE)
```
To quickly sort the word types by their frequency, we can use the `dfm()` command to create a matrix of counts of each word type -- a document-frequency matrix. In this case there is only one document, the entire book.
```{r eval=TRUE}
# ten most frequent words
moby_dfm <- dfm(moby_word_v)
moby_dfm
```
Getting the list of the most frequent 10 terms is easy, using `textstat_frequency()`.
```{r}
library("quanteda.textstats")
textstat_frequency(moby_dfm, n = 10)
```
Finally, if we wish to plot the most frequent (50) terms, we can supply the results of `textstat_frequency()` to `ggplot()` to plot their frequency by their rank:
```{r fig.width = 8}
# plot frequency of 50 most frequent terms
library("ggplot2")
theme_set(theme_minimal())
textstat_frequency(moby_dfm, n = 50) |>
ggplot(aes(x = rank, y = frequency)) +
geom_point() +
labs(x = "Frequency rank", y = "Term frequency")
```
For direct comparison with the next chapter, we also create the sorted list of the most frequently found words using this:
```{r}
sorted_moby_freqs_t <- topfeatures(moby_dfm, n = nfeat(moby_dfm))
```
# 3 Accessing and Comparing Word Frequency Data
## 3.1 Accessing Word Data
We can query the document-frequency matrix to retrieve word frequencies, as with a normal matrix:
```{r eval=TRUE}
# frequencies of "he" and "she" - these are matrixes, not numerics
sorted_moby_freqs_t[c("he", "she", "him", "her")]
# another method: indexing the dfm
moby_dfm[, c("he", "she", "him", "her")]
sorted_moby_freqs_t[1]
sorted_moby_freqs_t["the"]
# term frequency ratios
sorted_moby_freqs_t["him"] / sorted_moby_freqs_t["her"]
sorted_moby_freqs_t["he"] / sorted_moby_freqs_t["she"]
```
Total number of tokens:
```{r}
ntoken(moby_dfm)
sum(sorted_moby_freqs_t)
```
## 3.2 Recycling
Relative term frequencies:
```{r}
sorted_moby_rel_freqs_t <- sorted_moby_freqs_t / sum(sorted_moby_freqs_t) * 100
sorted_moby_rel_freqs_t["the"]
# by weighting the dfm directly
moby_dfm_pct <- dfm_weight(moby_dfm, scheme = "prop") * 100
dfm_select(moby_dfm_pct, pattern = "the")
```
Plotting the most frequent terms, replicating the plot from the book:
```{r}
plot(sorted_moby_rel_freqs_t[1:10], type = "b",
xlab = "Top Ten Words", ylab = "Percentage of Full Text", xaxt = "n")
axis(1,1:10, labels = names(sorted_moby_rel_freqs_t[1:10]))
```
Plotting the most frequent terms using **ggplot2**:
```{r}
textstat_frequency(moby_dfm_pct, n = 10) |>
ggplot(aes(x = reorder(feature, -rank), y = frequency)) +
geom_bar(stat = "identity") + coord_flip() +
labs(x = "", y = "Term Frequency as a Percentage")
```
# 4 Token Distribution Analysis
## 4.1 Dispersion plots
A dispersion plot allows us to visualize the occurrences of particular terms throughout the text. The object returned by the `kwic` function can be plotted to display a dispersion plot. The **quanteda** `textplot_` objects are based on **ggplot2**, so you can easily change the plot, for example by adding custom title.
```{r eval=TRUE, fig.width=8, fig.height=1.5}
# using words from tokenized corpus for dispersion
library("quanteda.textplots")
textplot_xray(kwic(novel_v_toks, pattern = "whale")) +
ggtitle("Lexical dispersion")
```
To produce multiple dispersion plots for comparison, you can simply send more than one `kwic()` output to `textplot_xray()`:
```{r eval=TRUE, fig.width=8, fig.height=2.5}
textplot_xray(
kwic(novel_v_toks, pattern = "whale"),
kwic(novel_v_toks, pattern = "Ahab")) +
ggtitle("Lexical dispersion")
```
## 4.2 Searching with regular expression
```{r}
# identify the chapter break locations
chap_positions_v <- kwic(novel_v_toks, phrase(c("CHAPTER \\d")), valuetype = "regex")$from
head(chap_positions_v)
```
## 4.2 Identifying chapter breaks
Splitting the text into chapters means that we will have a collection of documents, which makes this a good time to make a `corpus` object to hold the texts. Initially, we make a single-document corpus, and then use the `corpus_segment()` function to split this by the string which specifies the chapter breaks.
Because of the header information, however, we want to discard the first part. We can do this by segmenting the text according to the first chapter, "CHAPTER 1. Loomings.", which is preceded by 5 newlines.
```{r}
chapters_char <-
data_char_mobydick |>
char_segment(pattern = "\\n{5}CHAPTER 1\\. Loomings\\.\\n",
valuetype = "regex", remove_pattern = FALSE)
sapply(chapters_char, substring, 1, 100)
# remove header segment
chapters_char <- chapters_char[-1]
cat(substring(chapters_char, 1, 200))
```
Now we can segment the text based on the chapter titles. These titles are automatically extracted into the `pattern` document variables, and the text of each chapter becomes the text of each new document unit. To tidy this up, we can remove the trailing `\n` character, using `stri_trim_both()`, since the `\n` is a member of the "whitespace" group.
```{r}
chapters_corp <- chapters_char |>
corpus() |>
corpus_segment(pattern = "CHAPTER\\s\\d+.*\\n\\n", valuetype = "regex")
chapters_corp$pattern <- stringi::stri_trim_both(chapters_corp$pattern)
chapters_corp <- corpus_subset(chapters_corp, chapters_corp != "")
summary(chapters_corp, 10)
```
For better reference, let's also rename the document labels with these chapter headings:
```{r}
docnames(chapters_corp) <- chapters_corp$pattern
```
### 4.4.5 barplots of whale and ahab
With the corpus split into chapters, we can use the `dfm()` function to create a matrix of counts of each word in each chapter -- a document-frequency matrix.
```{r eval=TRUE, fig.width=8}
# create a dfm
chap_dfm <- tokens(chapters_corp) |>
dfm()
# extract row with count for "whale"/"ahab" in each chapter
# and convert to data frame for plotting
whales_ahabs_df <- chap_dfm |>
dfm_keep(pattern = c("whale", "ahab")) |>
convert(to = "data.frame")
whales_ahabs_df$chapter <- 1:nrow(whales_ahabs_df)
ggplot(data = whales_ahabs_df, aes(x = chapter, y = whale)) +
geom_bar(stat = "identity") +
labs(x = "Chapter",
y = "Frequency",
title = 'Occurrence of "whale"')
ggplot(data = whales_ahabs_df, aes(x = chapter, y = ahab)) +
geom_bar(stat = "identity") +
labs(x = "Chapter",
y = "Frequency",
title = 'Occurrence of "ahab"')
```
The above plots are raw frequency plots. For relative frequency plots, (word count divided by the length of the chapter) we can weight the document-frequency matrix. To obtain expected word frequency per 100 words, we multiply by 100. To get a feel for what the resulting weighted dfm (document-feature matrix) looks like, you can inspect it with the `head` function, which prints the first few rows and columns.
```{r eval=TRUE, fig.width=8}
rel_dfm <- dfm_weight(chap_dfm, scheme = "prop") * 100
head(rel_dfm)
# subset dfm and convert to data.frame object
rel_chap_freq <- rel_dfm |>
dfm_keep(pattern = c("whale", "ahab")) |>
convert(to = "data.frame")
rel_chap_freq$chapter <- 1:nrow(rel_chap_freq)
ggplot(data = rel_chap_freq, aes(x = chapter, y = whale)) +
geom_bar(stat = "identity") +
labs(x = "Chapter", y = "Relative frequency",
title = 'Occurrence of "whale"')
ggplot(data = rel_chap_freq, aes(x = chapter, y = ahab)) +
geom_bar(stat = "identity") +
labs(x = "Chapter", y = "Relative frequency",
title = 'Occurrence of "ahab"')
```
# 5 Correlation
## 5.2 Correlation Analysis
Correlation analysis (and many other similarity measures) can be constructed using fast, sparse means through the `textstat_simil()` function. Here, we select feature comparisons for just "whale" and "ahab", and convert this into a matrix as in the book. Because correlations are sensitive to document length, we first convert this into a relative frequency using `dfm_weight()`.
```{r}
dfm_weight(chap_dfm, scheme = "prop") |>
textstat_simil(y = chap_dfm[, c("whale", "ahab")], method = "correlation", margin = "features") |>
as.matrix() |>
head(2)
```
With the ahab frequency and whale frequency vectors extracted from the dfm, it is easy to calculate the significance of the correlation.
## 5.4 Testing Correlation with Randomization
```{r, fig.width=8}
cor_data_df <- dfm_weight(chap_dfm, scheme = "prop") |>
dfm_keep(pattern = c("ahab", "whale")) |>
convert(to = "data.frame")
# sample 1000 replicates and create data frame
n <- 1000
samples <- data.frame(
cor_sample = replicate(n, cor(sample(cor_data_df$whale), cor_data_df$ahab)),
id_sample = 1:n
)
# plot distribution of resampled correlations
ggplot(data = samples, aes(x = cor_sample, y = after_stat(density))) +
geom_histogram(colour = "black", binwidth = 0.01) +
geom_density(colour = "red") +
labs(x = "Correlation Coefficient", y = NULL,
title = "Histogram of Random Correlation Coefficients with Normal Curve")
```
# 6 Measures of Lexical Variety
## 6.2 Mean word frequency
```{r}
# length of the book in chapters
ndoc(chapters_corp)
# chapter names
docnames(chapters_corp) |> head()
```
Calculating the mean word frequencies is easy:
```{r}
# for first few chapters
ntoken(chapters_corp) |> head()
# average
(ntoken(chapters_corp) / ntype(chapters_corp)) |> head()
```
## 6.3 Extracting Word Usage Means
Since the quotient of the number of tokens and number of types is a vector, we
can simply feed this to `plot()` using the pipe operator:
```{r, fig.width = 8}
(ntoken(chapters_corp) / ntype(chapters_corp)) |>
plot(type = "h", ylab = "Mean word frequency")
```
For the scaled plot:
```{r, fig.width = 8}
(ntoken(chapters_corp) / ntype(chapters_corp)) |>
scale() |>
plot(type = "h", ylab = "Scaled mean word frequency")
```
## 6.4 Ranking the values
```{r}
mean_word_use_m <- (ntoken(chapters_corp) / ntype(chapters_corp))
sort(mean_word_use_m, decreasing = TRUE) |> head()
```
## 6.5 Calculating the TTR
Measures of lexical diversity can be estimated using `textstat_lexdiv()`. The TTR (Type-Token Ratio), a measure used in section 6.5, can be calculated for each document of the `dfm`.
```{r}
tokens(chapters_corp) |>
dfm() |>
textstat_lexdiv(measure = "TTR") |>
head(n = 10)
```
# 7 Hapax Richness
Another measure of lexical diversity is Hapax richness, defined as the number of words that occur only once divided by the total number of words. We can calculate Hapax richness very simply by using a logical operation on the document-feature matrix, to return a logical value for each term that occurs once, and then sum these to get a count.
```{r}
# hapaxes per document
rowSums(chap_dfm == 1) |> head()
# as a proportion
hapax_proportion <- rowSums(chap_dfm == 1) / ntoken(chap_dfm)
head(hapax_proportion)
```
To plot this:
```{r, fig.width=8}
barplot(hapax_proportion, beside = TRUE, col = "grey", names.arg = seq_len(ndoc(chap_dfm)))
```
# 8 Do it KWIC
For this, and the next chapter, we simply use **quanteda**'s excellent `kwic()` function. To find the indexes of the token positions for "gutenberg", for instance, we use the following, which returns a data.frame with the name `from` indicating the index position of the start of the token match:
```{r}
data_tokens_mobydick <- tokens(data_char_mobydick)
gutenberg_kwic <- kwic(data_tokens_mobydick, pattern = "gutenberg")
head(gutenberg_kwic$from, 10)
```
# 9 Do it KWIC (Better)
This is going to be super easy since we don't need to reinvent the wheel here, since `kwic()` already does all that we need.
Let's create a corpus containing _Moby Dick_ but also Jane Austen's _Sense and Sensibility_.
```{r, eval=FALSE}
data_char_senseandsensibility <- as.character(readtext::readtext("http://www.gutenberg.org/files/161/161-0.txt"))
names(data_char_senseandsensibility) <- "Sense and Sensibility"
litcorpus <- corpus(c(data_char_mobydick, data_char_senseandsensibility))
```
```{r, eval=TRUE, echo=FALSE}
load("data_char_mobydick.rda")
load("data_char_senseandsensibility.rda")
litcorpus <- corpus(c(data_char_mobydick, data_char_senseandsensibility))
```
Now we can use `kwic()` to find out where in each novel this occurred:
```{r}
(dogkwic <- kwic(tokens(litcorpus), pattern = "dog"))
```
We can plot this easily too, as a lexical dispersion plot. By specifying the scale as "absolute", we are looking at absolute token index position rather than relative position, and therefore we see that _Moby Dick_ is nearly twice as long as _Sense and Sensibility_.
```{r, fig.width = 8, fig.height=3}
textplot_xray(dogkwic, scale = "absolute")
```
# 10 Text Quality, Text Variety, and Parsing XML
# 11 Clustering
Chapter 11 describes how to detect clusters in a corpus. While the book uses the `XMLAuthorCorpus`, we describe clustering using U.S. State of the Union addresses included in the **quanteda.corpora** package. We trim the corpus with `dfm_trim()` by keeping only those words that occur at least five times in the corpus and in at least three speeches.
```{r}
library(quanteda.corpora)
pres_dfm <- tokens(corpus_subset(data_corpus_sotu, Date > "1980-01-01"), remove_punct = TRUE) |>
tokens_wordstem("en") |>
tokens_remove(stopwords("en")) |>
dfm() |>
dfm_trim(min_termfreq = 5, min_docfreq = 3)
# hierarchical clustering - get distances on normalized dfm
pres_dist_mat <- dfm_weight(pres_dfm, scheme = "prop") |>
textstat_dist(method = "euclidean") |>
as.dist()
# hiarchical clustering the distance object
pres_cluster <- hclust(pres_dist_mat)
# label with document names
pres_cluster$labels <- docnames(pres_dfm)
# plot as a dendrogram
plot(pres_cluster, xlab = "", sub = "",
main = "Euclidean Distance on Normalized Token Frequency")
```
# 12 Classification
# 13 Topic Modelling
Finally, Jockers' book introduces topic modelling of a corpus and the visualisation through wordclouds. We can easily apply functions from the **topicmodels** package by using **quanteda**'s `convert()` function. In our example, we use the Irish budget speeches from 2010 (`data_corpus_irishbudget2010`) and classify 20 topics using Latent Dirichlet Allocation.
```{r}
data(data_corpus_irishbudget2010, package = "quanteda.textmodels")
dfm_speeches <- tokens(data_corpus_irishbudget2010, remove_punct = TRUE, remove_numbers = TRUE) |>
tokens_remove(stopwords("en")) |>
dfm() |>
dfm_trim(min_termfreq = 4, max_docfreq = 10)
library(topicmodels)
LDA_fit_20 <- convert(dfm_speeches, to = "topicmodels") |>
LDA(k = 20)
# get top five terms per topic
get_terms(LDA_fit_20, 5)
```