Written and maintained by CASRAI Editorial Board
Published
On this page
A structural topic model (STM) discovers topics in a text collection while incorporating metadata about each document. In the R package stm, prevalence covariates model how much a topic is discussed, and content covariates model the words used within it. Start by deciding which of these quantities answers your research question; then preserve document–metadata alignment throughout preprocessing, fitting and interpretation.
What stm is used for in research
STM connects machine-assisted reading to questions about document characteristics. A political researcher can examine how topic proportions vary with party identification or time, while a content model can examine differences in vocabulary within a shared topic. The authors’ project overview identifies both capabilities, alongside diagnostics, uncertainty estimation and topic-correlation tools.
Each document can contain several topics. Each topic is a distribution over words, and a document’s topic proportions sum to one. This makes an STM different from assigning every response to one exclusive category. It also means a topic label is an interpretation of word distributions and documents, rather than a category supplied to the model in advance.
The authors’ Journal of Statistical Software paper distinguishes prevalence from content throughout its worked analysis. Without covariates, the model reduces to a correlated topic model. Adding metadata changes the statistical specification; adding a more descriptive topic name does not.
For the broader statistical background, see topic modeling and document-topic distributions. This workflow concentrates on fitting stm with covariates and interpreting its outputs, rather than reproducing an LDA derivation.
How to install or access stm
Install the R package from its official CRAN record. That record provides the package source, platform binaries, reference manual and vignette. The package declares R 3.5.0 or later and an MIT license with an accompanying license file. Use the official package record for installation requirements.
In R, run install.packages("stm"), followed by library(stm). Open the authors’ tutorial with vignette("stmVignette"), and use help("stm") for fitting arguments. The current reference manual documents individual functions, including preprocessing, model search and effect estimation.
If R itself is new to you, the R statistical programming overview provides context. The commands below belong to an R session. Save them together so that the preprocessing objects and model formulas remain part of the same analysis.
How to fit a structural topic model step by step
This walkthrough adapts the package’s documented Gadarian survey example. Its open-ended immigration responses have accompanying treatment and party-identification variables. The treatment prompt asked respondents to describe what made them anxious about immigration; the control prompt asked about immigration. The example demonstrates mechanics, without asserting any fitted findings.
-
Load texts and their metadata together. Run
data("gadarian", package = "stm"). The text field isopen.ended.response; the covariates used below aretreatmentandpid_rep. For your own corpus, the authors’ workflow starts with one document per row alongside its metadata. Resolve missing values in variables used by the model before fitting. -
Process the text. Run
processed = textProcessor(gadarian$open.ended.response, metadata = gadarian). The documented processing includes lowercasing, stop-word removal, punctuation removal and stemming. Inspect the resulting vocabulary before deciding that these transformations suit your research question. Stemming combines word forms; the displayed terms may therefore differ from ordinary spelling. -
Prepare the analysis objects. Run
out = prepDocuments(processed$documents, processed$vocab, processed$meta). Useout$documents,out$vocabandout$metatogether afterward. The function updates metadata when filtering removes documents. Mixing filtered documents with the original metadata can attach the wrong characteristics to a response. -
Compare topic counts. The documented survey example uses
searchKwith candidate counts 5, 10 and 15. Runset.seed(2138), thenkcheck = searchK(out$documents, out$vocab, K = c(5, 10, 15), prevalence = ~ treatment + s(pid_rep), data = out$meta), followed byplot(kcheck). These are candidate resolutions, not a recommendation that every survey should have those topic counts. -
Fit a candidate model. For an illustrative five-topic specification, run
fit = stm(documents = out$documents, vocab = out$vocab, K = 5, prevalence = ~ treatment + s(pid_rep), data = out$meta, init.type = "Spectral"). Heres(pid_rep)is the package’s spline transformation. Replace the illustrative topic count with your justified selection after examining diagnostics and texts. -
Inspect words and responses. Run
labelTopics(fit)andplot(fit, type = "summary"). Retrieve examples withfindThoughts(fit, texts = out$meta$open.ended.response, topics = 1, n = 3). Passing the retained text field preserves the same row order as the fitted documents. Read the responses before naming Topic 1. -
Estimate covariate relationships. Run
effects = estimateEffect(1:5 ~ treatment + s(pid_rep), stmobj = fit, metadata = out$meta, uncertainty = "Global"), thensummary(effects, topics = 1). The left side identifies the topics being analyzed. If the final model has a different topic count, change that range to match it.
For a content question, the authors show a separate model that includes both prevalence = ~ rating + s(day) and content = ~ rating in their political-blog example. A content formula changes the model and its topics. Reinspect and relabel that new model rather than carrying topic numbers over from a prevalence-only fit.
How to read the output
Read three outputs separately: topic words, document-topic proportions and covariate relationships. The fitted theta matrix has a row for each document and a column for each topic. An entry describes the estimated share of that document allocated to that topic. It does not mean the whole document belongs exclusively to it.
labelTopics reports several word rankings. Highest-probability words indicate common vocabulary within a topic; FREX balances frequency with exclusivity to that topic. The authors recommend examining both word profiles and example documents. A convincing label should describe the responses themselves, rather than simply repeating the first keyword.
searchK offers held-out likelihood, residual analysis, semantic coherence and exclusivity. Coherence reflects co-occurrence of prominent topic words, while exclusivity helps distinguish topics from one another. The authors warn that high coherence can arise from a few topics dominated by common words. Assess these diagnostics jointly, then inspect the topics at the proposed resolution.
There is no single correct topic count for every corpus. A model can split a broad issue into several narrower themes as K increases. Record the substantive reason for the selected resolution, rather than presenting one diagnostic maximum as a discovery of the corpus’s uniquely true structure.
estimateEffect regresses topic proportions on metadata while accounting for uncertainty in those proportions. The authors describe the Global approach as incorporating topic-estimation uncertainty through the method of composition. Choosing None leaves that component out and generally produces narrower intervals. Keep the covariates used in effect estimation represented in the topic model.
For an analysis record, retain the corpus definition, preprocessing choices, retained document identifiers, topic-count comparison, final formulas and evidence supporting topic labels. This is a practical application of reproducible research practices. The data table below distinguishes questions, outputs and interpretation boundaries across the documented workflows.
Troubleshooting stm
Texts and covariates no longer line up. Return to the objects produced by prepDocuments. The authors explain that removing an empty document also removes its metadata row. Keep the filtered objects together, and use retained identifiers to trace results back to original responses. Check that any separately stored text vector underwent the same filtering.
Filtering removes too much material. Inspect the vocabulary and use plotRemoved to examine candidate thresholds before adopting one. A threshold used for a large political-blog corpus is not automatically appropriate for brief survey answers. Changes to preprocessing change the evidence available to the model, so compare their effects on retained texts as well as vocabulary size.
Topic-count diagnostics vary between runs. The reference manual specifically warns that held-out results can be unstable with short documents or few held-out observations. A fixed seed helps reproduce a particular comparison; it does not increase the amount of held-out evidence. Use the quantitative diagnostics alongside the authors’ recommended inspection of words and documents.
The model reaches its iteration limit. Inspect the convergence messages and the variational bound. The authors show plot(fit$convergence$bound, type = "l") for this purpose and document continuing estimation through the model argument. Reaching a maximum iteration count is different from satisfying the convergence criterion.
The topic name seems implausible. Return to FREX words and the retrieved responses. Consider whether the interpretation comes from the topic’s text or from your expectations about the covariates. For studies organized around a predefined coding framework, compare the analytical purpose with content analysis before treating model-discovered themes as that framework.
Free alternatives to stm
Alternative topic-modeling tools answer different questions. The following comparison concerns documented methods and outputs. It does not establish a benchmark winner or imply that another tool reproduces STM’s covariate model.
| Alternative | Documented approach | Research use to consider |
|---|---|---|
| scikit-learn LDA | Generative probabilistic modeling of document-topic mixtures. | A Python implementation when the task is probabilistic topic modeling. |
| scikit-learn NMF | Factorization into nonnegative component matrices; its documentation includes topic extraction. | Exploring term-based components through matrix factorization. |
| BERTopic | A modular workflow using embeddings, dimensionality reduction, clustering and topic representations. | Exploring embedding-based document clusters and their descriptions in Python. |
What is LDA in NLP?
LDA means Latent Dirichlet Allocation. Blei, Ng and Jordan’s original paper describes a generative probabilistic model for collections such as text corpora, representing documents through topic mixtures. STM builds on probabilistic topic modeling while bringing document metadata into the specification.
What are the different topic modelling techniques?
Relevant families include probabilistic models such as LDA and STM, nonnegative matrix factorization, and embedding-based clustering workflows such as BERTopic. The scikit-learn decomposition guide documents LDA and NMF. Choose among these approaches by the quantity your study needs to estimate and the output you can validate.
Is BERTopic better than LDA?
There is no universal winner established by these descriptions. BERTopic’s developer documentation describes a default sequence of sentence-transformers, UMAP, HDBSCAN and c-TF-IDF, whereas LDA models topic mixtures probabilistically. For an STM study, assess whether the research question requires covariate-dependent prevalence or content before comparing tools on topic labels alone.
Can ChatGPT do topic modeling?
ChatGPT can contribute to a topic-modeling workflow by generating topic descriptions. BERTopic documents an OpenAI representation model for labels, summaries, phrases and keywords. That role concerns representation. A generated label does not supply the fitted STM’s topic proportions, covariate estimates or uncertainty; retain those statistical outputs when reporting the analysis.
Frequently asked questions
Can ChatGPT do topic modeling?
It can help describe topics; BERTopic documents an OpenAI integration for that purpose. Distinguish generated descriptions from the fitted model and its statistical estimates.
What is LDA in NLP?
Latent Dirichlet Allocation is a probabilistic model representing documents through mixtures of topics. STM adds the ability to incorporate document metadata.
Is BERTopic better than LDA?
The appropriate method depends on the research task. Compare the needed outputs, inspect the resulting topics and avoid treating one tool’s descriptive labels as evidence of universal superiority.
What are the different topic modelling techniques?
Examples include LDA, structural and correlated topic models, NMF, and embedding-based workflows such as BERTopic. They differ in their statistical structure and outputs.
Sources
- STM authors: An R Package for the Structural Topic Model, checked 2026-12-03.
- CRAN: stm package record, checked 2026-12-03.
- STM authors: package reference manual, checked 2026-12-03.
- Roberts, Stewart and Tingley: stm: An R Package for Structural Topic Models, Journal of Statistical Software, 2019, checked 2026-12-03.
- Blei, Ng and Jordan: Latent Dirichlet Allocation, Journal of Machine Learning Research, 2003, checked 2026-12-03.
- BERTopic developers: installation, quick start, representations and modularity, checked 2026-12-03.
- scikit-learn developers: Decomposing signals in components, checked 2026-12-03.
Data: Topic-analysis questions, model components and outputs
An original crosswalk compiled from the stm authors’ software paper and reference manual, the original LDA abstract and BERTopic developer documentation. It connects analytical questions to documented model components, outputs and the source supporting each row.
| Analytical question | Method or component | Documented output or role | Interpretation boundary | Primary source |
|---|---|---|---|---|
| How does attention vary with document metadata? | STM prevalence covariates | Document-topic proportions depend on document covariates. | Prevalence describes how much a topic contributes to a document. | https://www.jstatsoft.org/index.php/jss/article/view/v091i02/1319 |
| How does word use vary within a topic? | STM content covariate | Topic-word distributions vary with a document content covariate. | A new content model may change topic content and numbering. | https://www.jstatsoft.org/index.php/jss/article/view/v091i02/1319 |
| How are topic proportions related to covariates? | stm estimateEffect | Regressions of document topic proportions on metadata with measurement uncertainty. | Global includes uncertainty; None omits topic-proportion measurement uncertainty. | https://cran.r-project.org/web/packages/stm/refman/stm.html |
| How can documents be represented as topic mixtures? | Latent Dirichlet Allocation | A generative probabilistic model representing documents through topic probabilities. | The original abstract describes a hierarchical Bayesian topic-mixture model. | https://jmlr.org/papers/v3/blei03a.html |
| How can discovered topics be described with generated text? | BERTopic OpenAI representation model | Labels, summaries, phrases and keywords for topic representations. | The documented role is representation of topics. | https://maartengr.github.io/BERTopic/index.html |
Sources
- Roberts, Stewart and Tingley: stm: An R Package for Structural Topic Models (2019) (accessed 2026-12-03)
- stm reference manual (accessed 2026-12-03)
- BERTopic: topic representations and modularity (accessed 2026-12-03)
- Latent Dirichlet Allocation (accessed 2026-12-03)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







