Skip to content

Instantly share code, notes, and snippets.

@sagarnanduunc
Created March 13, 2018 20:01
Show Gist options
  • Select an option

  • Save sagarnanduunc/3da295e9933c6935e7963db3d87ce661 to your computer and use it in GitHub Desktop.

Select an option

Save sagarnanduunc/3da295e9933c6935e7963db3d87ce661 to your computer and use it in GitHub Desktop.
R helper function for topic modeling
analyzeTopics <- function(ctmFit,fileLoc){
td_beta <- tidy(ctmFit, matrix = "beta")
# helper functions (from David Robinson's R Package)
scale_x_reordered <- function(..., sep = "___") {
reg <- paste0(sep, ".+$")
ggplot2::scale_x_discrete(labels = function(x) gsub(reg, "", x), ...)
}
reorder_within <- function(x, by, within, fun = mean, sep = "___", ...) {
new_x <- paste(x, within, sep = sep)
stats::reorder(new_x, by, FUN = fun)
}
# Examine the topics
td_beta %>%
group_by(topic) %>%
top_n(8, beta) %>%
ungroup() %>%
mutate(topic = paste0("Topic ", topic),
term = reorder_within(term, beta, topic)) %>%
ggplot(aes(term, beta, fill = topic)) +
geom_col(alpha = 0.8, show.legend = FALSE) +
facet_wrap(~ topic, ncol = 4, scales = "free") +
scale_x_reordered() +
coord_flip() +
labs(x = "",
y = "")
#saveing the plot
ggsave(fileLoc)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment