
Compute TF–IDF on three fictional documents. TF is relative frequency and IDF is log(N/df). Their product highlights distinguishing terms.
Run Rscript --vanilla analysis.R results.csv and quarto render dashboard.qmd. The same synthetic result table can be connected to Superset using the SQL below.
Calculated results
| term | max_tfidf |
|---|---|
| city | 0.54931 |
| forest | 0.54931 |
| hill | 0.27465 |
| park | 0.10137 |
| river | 0.20273 |
| tram | 0.27465 |
| water | 0.27465 |
analysis.R
# Синтетические данные и расчёт метрик для обоих дашбордов.
set.seed(2026)
documents <- c("forest river forest hill", "city tram park city", "river park water river")
tokens <- strsplit(documents, " ", fixed = TRUE)
dictionary <- sort(unique(unlist(tokens)))
counts <- sapply(tokens, function(words) table(factor(words, levels = dictionary)))
tf <- sweep(counts, 2, colSums(counts), "/")
idf <- log(length(documents) / rowSums(counts > 0))
result <- data.frame(term = dictionary, max_tfidf = apply(tf * idf, 1, max))
# Проверяет конечность основной метрики перед экспортом.
stopifnot(nrow(result) > 1, all(is.finite(result$max_tfidf)))
if (sys.nframe() == 0L) {
arguments <- commandArgs(trailingOnly = TRUE)
stopifnot(length(arguments) == 1L)
write.csv(result, arguments[1], row.names = FALSE)
}
dashboard.qmd
---
title: "Текстовый анализ TF–IDF"
lang: ru
format: dashboard
execute:
echo: false
---
```{r}
source("analysis.R", local = TRUE)
```
# Результаты
## Row
### График
```{r}
x <- result$term
y <- result$max_tfidf
if (is.numeric(x)) {
plot(x, y, xlab = "term", ylab = "max_tfidf", pch = 19, col = "#245d76")
} else {
par(mar = c(7, 4, 2, 1))
barplot(y, names.arg = x, ylab = "max_tfidf", las = 2, col = "#245d76")
}
```
### Таблица
```{r}
knitr::kable(result, digits = 3)
```
## Row
### Как читать результат
TF — относительная частота слова. IDF = log(N/df) уменьшает вес широко распространённых слов. Произведение TF на IDF измеряет полезность слова для документа.
superset.sql
-- Замените portfolio_results именем таблицы, куда импортирован results.csv.
SELECT term, max_tfidf
FROM portfolio_results
ORDER BY term;