# NOT RUN {
# }
# NOT RUN {
library(mallet)
library(dplyr)
data("AssociatedPress", package = "topicmodels")
td <- tidy(AssociatedPress)
# mallet needs a file with stop words
tmp <- tempfile()
writeLines(stop_words$word, tmp)
# two vectors: one with document IDs, one with text
docs <- td %>%
group_by(document = as.character(document)) %>%
summarize(text = paste(rep(term, count), collapse = " "))
docs <- mallet.import(docs$document, docs$text, tmp)
# create and run a topic model
topic_model <- MalletLDA(num.topics = 4)
topic_model$loadDocuments(docs)
topic_model$train(20)
# tidy the word-topic combinations
td_beta <- tidy(topic_model)
td_beta
# Examine the four topics
td_beta %>%
group_by(topic) %>%
top_n(8, beta) %>%
ungroup() %>%
mutate(term = reorder(term, beta)) %>%
ggplot(aes(term, beta)) +
geom_col() +
facet_wrap(~ topic, scales = "free") +
coord_flip()
# find the assignments of each word in each document
assignments <- augment(topic_model, td)
assignments
# }
# NOT RUN {
# }
Run the code above in your browser using DataLab