#| include = FALSE knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "man/figures/README-", out.width = "100%", message = FALSE ) suppressPackageStartupMessages(library(ggplot2)) theme_set(theme_light())
Authors: Julia Silge, David Robinson
License: MIT
Using tidy data principles can make many text mining tasks easier, more effective, and consistent with tools already in wide use. Much of the infrastructure needed for text mining with tidy data frames already exists in packages like dplyr, broom, tidyr, and ggplot2. In this package, we provide functions and supporting data sets to allow conversion of text to and from tidy formats, and to switch seamlessly between tidy tools and existing text mining packages. Check out our book to learn more about text mining using tidy data principles.
You can install this package from CRAN:
#| eval = FALSE install.packages("tidytext")
Or you can install the development version from GitHub with remotes:
#| eval = FALSE library(remotes) install_github("juliasilge/tidytext")
unnest_tokens
functionThe novels of Jane Austen can be so tidy! Let's use the text of Jane Austen's 6 completed, published novels from the janeaustenr package, and transform them to a tidy format. janeaustenr provides them as a one-row-per-line format:
library(janeaustenr) library(dplyr) original_books <- austen_books() %>% group_by(book) %>% mutate(line = row_number()) %>% ungroup() original_books
To work with this as a tidy dataset, we need to restructure it as 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:
library(tidytext) tidy_books <- original_books %>% unnest_tokens(word, text) tidy_books
This function uses the tokenizers package to separate each line into words. 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 a one-word-per-row format, we can manipulate it with tidy tools like dplyr. We can remove stop words (available via the function get_stopwords()
) with an anti_join()
.
tidy_books <- tidy_books %>% anti_join(get_stopwords())
We can also use count()
to find the most common words in all the books as a whole.
tidy_books %>% count(word, sort = TRUE)
Sentiment analysis can be implemented as an inner join. Three sentiment lexicons are available via the get_sentiments()
function. Let's examine how sentiment changes across each novel. Let's find a sentiment score for each word using the Bing lexicon, then count the number of positive and negative words in defined sections of each novel.
#| fig.width = 8, #| fig.height = 10 library(tidyr) get_sentiments("bing") janeaustensentiment <- tidy_books %>% inner_join(get_sentiments("bing"), by = "word", relationship = "many-to-many") %>% count(book, index = line %/% 80, sentiment) %>% pivot_wider(names_from = sentiment, values_from = n, values_fill = 0) %>% mutate(sentiment = positive - negative) janeaustensentiment
Now we can plot these sentiment scores across the plot trajectory of each novel.
#| fig.width = 7, #| fig.height = 7, #| fig.alt = "Sentiment scores across the trajectories of Jane Austen's six published novels", #| warning = FALSE library(ggplot2) ggplot(janeaustensentiment, aes(index, sentiment, fill = book)) + geom_col(show.legend = FALSE) + facet_wrap(vars(book), ncol = 2, scales = "free_x")
For more examples of text mining using tidy data frames, see the tidytext vignette.
Some existing text mining datasets are in the form of a DocumentTermMatrix class (from the tm package). For example, consider the corpus of 2246 Associated Press articles from the topicmodels dataset.
library(tm) data("AssociatedPress", package = "topicmodels") AssociatedPress
If we want to analyze this with tidy tools, we need to transform it into a one-row-per-term data frame first with a tidy()
function. (For more on the tidy verb, see the broom package).
tidy(AssociatedPress)
We could find the most negative documents:
ap_sentiments <- tidy(AssociatedPress) %>% inner_join(get_sentiments("bing"), by = c(term = "word")) %>% count(document, sentiment, wt = count) %>% pivot_wider(names_from = sentiment, values_from = n, values_fill = 0) %>% mutate(sentiment = positive - negative) %>% arrange(sentiment)
Or we can join the Austen and AP datasets and compare the frequencies of each word:
#| fig.height = 8, #| fig.width = 8, #| fig.alt = 'Scatterplot for word frequencies in Jane Austen vs. AP news articles. Some words like "cried" are only common in Jane Austen, some words like "national" are only common in AP articles, and some word like "time" are common in both.' comparison <- tidy(AssociatedPress) %>% count(word = term) %>% rename(AP = n) %>% inner_join(count(tidy_books, word)) %>% rename(Austen = n) %>% mutate(AP = AP / sum(AP), Austen = Austen / sum(Austen)) comparison library(scales) ggplot(comparison, aes(AP, Austen)) + geom_point(alpha = 0.5) + geom_text(aes(label = word), check_overlap = TRUE, vjust = 1, hjust = 1) + scale_x_log10(labels = percent_format()) + scale_y_log10(labels = percent_format()) + geom_abline(color = "red")
For more examples of working with objects from other text mining packages using tidy data principles, see the vignette on converting to and from document term matrices.
This project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms. Feedback, bug reports (and fixes!), and feature requests are welcome; file issues or seek support here.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.