forked from dgrtwo/tidy-text-mining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
02-tidy-text.Rmd
230 lines (165 loc) · 11.9 KB
/
02-tidy-text.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
# The tidy text format {#tidytext}
```{r echo = FALSE}
library(knitr)
opts_chunk$set(message = FALSE, warning = FALSE, cache = TRUE)
options(width = 100, dplyr.width = 100)
library(ggplot2)
theme_set(theme_light())
```
We define the tidy text format as being a table with **one-term-per-row.** Structuring text data in this way means that it conforms to tidy data principles and can be manipulated with a set of consistent tools. This is worth contrasting with the ways text is often stored in text mining approaches.
* **Raw string**: Text can, of course, be stored as raw strings within R, and often text data is first read into memory in this form.
* **Corpus**: These types of objects typically annotate the raw string content with additional metadata and details.
* **Document-term matrix**: This is a sparse matrix describing a collection (i.e., a corpus) of documents with one row for each document and one column for each term. The value in the matrix is typically word count or tf-idf (see [Chapter 4](#tfidf)).
Let's hold off on exploring structures like a document-term matrix until [Chapter 6](#dtm), and get down to the basics of converting text to a tidy format.
## The `unnest_tokens` function
Emily Dickinson wrote some lovely text in her time.
```{r text}
text <- c("Because I could not stop for Death -",
"He kindly stopped for me -",
"The Carriage held but just Ourselves -",
"and Immortality")
text
```
This is a typical character vector that we might want to analyze. In order to turn it into a tidy text dataset, we first need to put it into a data frame.
```{r text_df, dependson = "text"}
library(dplyr)
text_df <- data_frame(line = 1:4, text = text)
text_df
```
Notice that this data frame isn't yet compatible with tidy tools. We can't filter out words or count which occur most frequently, since each row is made up of multiple combined words. We need to convert this so that it has **one-token-per-document-per-row**. A token, in this context, is a meaningful unit of text that we are interested in using for further analysis. Tokenization is the process of breaking up text into individual tokens, and it is most commonly done at the level of single words. Within our tidy text framework, we will both break the text into individual tokens *and* transform it to a tidy data structure.
To do this, we use tidytext's `unnest_tokens` function.
```{r dependson = "text_df", R.options = list(dplyr.print_max = 10)}
library(tidytext)
text_df %>%
unnest_tokens(word, text)
```
We've now split each row so that there is one token (word) in each row of the new data frame; the default tokenization in `unnest_tokens` is for single words, as shown here. Also notice:
* Other columns, such as the line number each word came from, are retained.
* Punctuation has been stripped.
* By default, `unnest_tokens` converts the tokens to lowercase, which makes them easier to compare or combine with other datasets. (Use the `to_lower = FALSE` argument to turn off this behavior).
Having the text data in this format lets us manipulate, process, and visualize the text using the standard set of tidy tools, namely dplyr, tidyr, ggplot2, and broom.
## Tidying the works of Jane Austen
Let's use the text of Jane Austen's 6 completed, published novels from the [janeaustenr](https://cran.r-project.org/package=janeaustenr) package [@R-janeaustenr], and transform them into a tidy format. The janeaustenr package provides these texts in a one-row-per-line format. Let’s start with that, annotate a `linenumber` quantity to keep track of lines in the original format, and use a regex to find where all the chapters are.
```{r original_books}
library(janeaustenr)
library(dplyr)
library(stringr)
original_books <- austen_books() %>%
group_by(book) %>%
mutate(linenumber = row_number(),
chapter = cumsum(str_detect(text, regex("^chapter [\\divxlc]",
ignore_case = TRUE)))) %>%
ungroup()
original_books
```
To work with this as a tidy dataset, we need to restructure it in the **one-token-per-row** format. The `unnest_tokens` function is a way to convert a dataframe with a text column to be one-token-per-row.
```{r tidy_books_raw, dependson = "original_books"}
library(tidytext)
tidy_books <- original_books %>%
unnest_tokens(word, text)
tidy_books
```
This function uses the [tokenizers package](https://github.com/ropensci/tokenizers) [@R-tokenizers] to separate each line of text in the original data frame into tokens. The default tokenizing is for words, but other options include characters, n-grams, sentences, lines, paragraphs, or separation around a regex pattern.
Now that the data is in one-word-per-row format, we can manipulate it with tidy tools like dplyr. We can remove stop words (kept in the tidytext dataset `stop_words`) with an `anti_join`.
```{r tidy_books, dependson = "tidy_books_raw"}
data(stop_words)
tidy_books <- tidy_books %>%
anti_join(stop_words)
```
We can also use `count` to find the most common words in all the books as a whole.
```{r dependson = "tidy_books"}
tidy_books %>%
count(word, sort = TRUE)
```
For example, this allows us to visualize the commonly used words using ggplot2.
```{r plot_count, dependson = "tidy_books", fig.width=6, fig.height=5}
library(ggplot2)
tidy_books %>%
count(word, sort = TRUE) %>%
filter(n > 600) %>%
mutate(word = reorder(word, n)) %>%
ggplot(aes(word, n)) +
geom_bar(stat = "identity") +
xlab(NULL) +
coord_flip()
```
We could pipe this straight into ggplot2 because of our consistent use of tidy tools.
## The gutenbergr package
Now that we've used the janeaustenr package, let's introduce the [gutenbergr](https://github.com/ropenscilabs/gutenbergr) package [@R-gutenbergr]. The gutenbergr package provides access to the public domain works from the [Project Gutenberg](https://www.gutenberg.org/) collection. The package includes tools both for downloading books (stripping out the unhelpful header/footer information), and a complete dataset of Project Gutenberg metadata that can be used to find works of interest. In this book, we will mostly use the function `gutenberg_download()` that downloads one or more works from Project Gutenberg by ID, but you can also use other functions to explore metadata, pair Gutenberg ID with title, author, language, etc., or gather information about authors. To learn more about gutenbergr, check out the [package's tutorial at rOpenSci](https://ropensci.org/tutorials/gutenbergr_tutorial.html), where it is one of rOpenSci's packages for data access.
## Word frequencies
A common task in text mining is to look at word frequencies, just like we have done above for Jane Austen's novels, and to compare frequencies across different texts. We can do this intuitively and smoothly using tidy data principles. We already have Jane Austen's works; let's get two more sets of texts to compare to. First, let's look at some science fiction and fantasy novels by H.G. Wells, who lived in the late 19th and early 20th centuries. Let's get [*The Time Machine*](https://www.gutenberg.org/ebooks/35), [*The War of the Worlds*](https://www.gutenberg.org/ebooks/36), [*The Invisible Man*](https://www.gutenberg.org/ebooks/5230), and [*The Island of Doctor Moreau*](https://www.gutenberg.org/ebooks/159).
```{r eval = FALSE}
library(gutenbergr)
hgwells <- gutenberg_download(c(35, 36, 5230, 159))
```
```{r hgwells, echo = FALSE}
load("data/hgwells.rda")
```
```{r tidy_hgwells, dependson = "hgwells"}
tidy_hgwells <- hgwells %>%
unnest_tokens(word, text) %>%
anti_join(stop_words)
```
Just for kicks, what are the most common words in these novels of H.G. Wells?
```{r dependson = "tidy_hgwells"}
tidy_hgwells %>%
count(word, sort = TRUE)
```
Now let's get some well-known works of the Brontë sisters, whose lives overlapped with Jane Austen's somewhat but who wrote in a rather different style. Let's get [*Jane Eyre*](https://www.gutenberg.org/ebooks/1260), [*Wuthering Heights*](https://www.gutenberg.org/ebooks/768), [*The Tenant of Wildfell Hall*](https://www.gutenberg.org/ebooks/969), [*Villette*](https://www.gutenberg.org/ebooks/9182), and [*Agnes Grey*](https://www.gutenberg.org/ebooks/767).
```{r eval = FALSE}
bronte <- gutenberg_download(c(1260, 768, 969, 9182, 766))
```
```{r echo = FALSE}
load("data/bronte.rda")
```
```{r tidy_bronte, dependson = "bronte"}
tidy_bronte <- bronte %>%
unnest_tokens(word, text) %>%
anti_join(stop_words)
```
What are the most common words in these novels of the Brontë sisters?
```{r dependson = "tidy_bronte"}
tidy_bronte %>%
count(word, sort = TRUE)
```
Interesting that "time", "eyes", and "hand" are in the top 10 for both H.G. Wells and the Brontë sisters.
Now, let's calculate the frequency for each word for the works of Jane Austen, the Brontë sisters, and H.G. Wells.
```{r frequency, dependson = c("tidy_bronte", "tidy_hgwells", "tidy_books")}
tidy_both <- bind_rows(
mutate(tidy_bronte, author = "Brontë Sisters"),
mutate(tidy_hgwells, author = "H.G. Wells"))
austen_percent <- tidy_books %>%
mutate(word = str_extract(word, "[a-z]+")) %>%
count(word) %>%
transmute(word, austen = n / sum(n))
frequency <- tidy_both %>%
mutate(word = str_extract(word, "[a-z]+")) %>%
count(author, word) %>%
mutate(other = n / sum(n)) %>%
left_join(austen_percent) %>%
ungroup()
```
We use `str_extract` here because the UTF-8 encoded texts from Project Gutenberg have some examples of words with underscores around them to indicate emphasis (like italics). The tokenizer treated these as words but we don't want to count "\_any\_" separately from "any". Now let's plot.
```{r plot_compare, dependson = "frequency", fig.width=10, fig.height=5.5}
library(scales)
ggplot(frequency, aes(x = other, y = austen, color = abs(austen - other))) +
geom_abline(color = "gray40", lty = 2) +
geom_jitter(alpha = 0.1, size = 2.5, width = 0.3, height = 0.3) +
geom_text(aes(label = word), check_overlap = TRUE, vjust = 1.5) +
scale_x_log10(labels = percent_format()) +
scale_y_log10(labels = percent_format()) +
scale_color_gradient(limits = c(0, 0.001), low = "darkslategray4", high = "gray75") +
facet_wrap(~author, ncol = 2) +
theme(legend.position="none") +
labs(y = "Jane Austen", x = NULL)
```
Words that are close to the line in these plots have similar frequencies in both sets of texts, for example, in both Austen and Brontë texts ("miss", "time", "day" at the upper frequency end) or in both Austen and Wells texts ("time", "day", "brother" at the high frequency end). Words that are far from the line are words that are found more in one set of texts than another. For example, in the Austen-Brontë plot, words like "elizabeth", "emma", and "edmund" (all proper nouns) are found in Austen's texts but not much in the Brontë texts, while words like "arthur", "dog", and "ham" are found in the Brontë texts but not the Austen texts. In comparing H.G. Wells with Jane Austen, Wells uses words like "beast", "island", "feet", and "black" that Austen does not, while Austen uses words like "family", "friend", "letter", and "dear" that Wells does not.
Overall, notice that the words in the Austen-Brontë plot are closer to the zero-slope line than in the Austen-Wells plot and also extend to lower frequencies; Austen and the Brontë sisters use more similar words than Austen and H.G. Wells. Also, we notice that not all the words are found in all three sets of texts and there are fewer points in the plot for Austen and H.G. Wells.
Let's quantify how similar and different these sets of word frequencies are using a correlation test. How correlated are the word frequencies between Austen and the Brontë sisters, and between Austen and Wells?
```{r cor_test, dependson = "frequency"}
cor.test(data = frequency[frequency$author == "Brontë Sisters",],
~ other + austen)
cor.test(data = frequency[frequency$author == "H.G. Wells",],
~ other + austen)
```
The relationship between the word frequencies is different between these sets of texts, as it appears in the plots.