
Standardize both features and compare within-cluster sums of squares for k = 1 through 6. The elbow shows where improvements start to diminish.
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
| k | within_ss |
|---|---|
| 1 | 208.0000 |
| 2 | 108.9400 |
| 3 | 19.8840 |
| 4 | 14.9570 |
| 5 | 11.3820 |
| 6 | 8.8958 |
analysis.R
# Синтетические данные и расчёт метрик для обоих дашбордов.
set.seed(2026)
group <- rep(1:3, each = 35)
points <- scale(cbind(rnorm(105, group * 4, 0.7), rnorm(105, c(0, 4, 0)[group], 0.8)))
within <- vapply(1:6, function(k) kmeans(points, k, nstart = 20)$tot.withinss, numeric(1))
result <- data.frame(k = 1:6, within_ss = within)
stopifnot(all(diff(within) < 0))
# Проверяет конечность основной метрики перед экспортом.
stopifnot(nrow(result) > 1, all(is.finite(result$within_ss)))
if (sys.nframe() == 0L) {
arguments <- commandArgs(trailingOnly = TRUE)
stopifnot(length(arguments) == 1L)
write.csv(result, arguments[1], row.names = FALSE)
}
dashboard.qmd
---
title: "Кластеризация K-means"
lang: ru
format: dashboard
execute:
echo: false
---
```{r}
source("analysis.R", local = TRUE)
```
# Результаты
## Row
### График
```{r}
x <- result$k
y <- result$within_ss
if (is.numeric(x)) {
plot(x, y, xlab = "k", ylab = "within_ss", pch = 19, col = "#245d76")
} else {
par(mar = c(7, 4, 2, 1))
barplot(y, names.arg = x, ylab = "within_ss", las = 2, col = "#245d76")
}
```
### Таблица
```{r}
knitr::kable(result, digits = 3)
```
## Row
### Как читать результат
K-means минимизирует сумму квадратов евклидовых расстояний до центров. Масштабирование делает вклад координат сопоставимым. Метод локтя помогает выбрать k.
superset.sql
-- Замените portfolio_results именем таблицы, куда импортирован results.csv.
SELECT k, within_ss
FROM portfolio_results
ORDER BY k;