## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>",
                      fig.width = 6, fig.height = 5, fig.align = "center")
set.seed(2026)

## ----half-circles-data--------------------------------------------------------
library(MergeKmeans)

n <- 1000
th <- runif(n, 0, pi)
x <- rbind(
  cbind(cos(th[1:500]), sin(th[1:500])),
  cbind(1 - cos(th[501:1000]), 0.45 - sin(th[501:1000])))
x <- x + matrix(rnorm(2 * n, sd = 0.1), n)
truth <- rep(1:2, each = 500)
plot(x, col = truth, pch = 20, asp = 1, xlab = "x1", ylab = "x2")

## ----half-circles-fit---------------------------------------------------------
fit <- MergeKmeans(x, K = 10, G = 2, linkage = "single", nstart = 25)
fit
table(estimated = fit$cluster, truth = truth)

## ----half-circles-plot--------------------------------------------------------
plot(fit, what = "classification", asp = 1)

## ----overlap-map--------------------------------------------------------------
plot(fit, what = "overlap")

## ----tree---------------------------------------------------------------------
plot(fit, what = "tree")
recut(fit, omega.star = 0.01)

## ----inscribed----------------------------------------------------------------
m <- 500
th2 <- runif(m, 0, 2 * pi)
y <- rbind(cbind(rnorm(m, 3, 0.2) * cos(th2), rnorm(m, 3, 0.2) * sin(th2)),
           matrix(rnorm(2 * m, sd = 0.4), m))
truth2 <- rep(1:2, each = m)
fit2 <- MergeKmeans(y, K = 12, G = 2, linkage = "single", nstart = 25)
table(estimated = fit2$cluster, truth = truth2)
plot(fit2, what = "classification", asp = 1)

## ----chooseK------------------------------------------------------------------
chooseK(x, K = seq(2, 20, by = 2), nstart = 10)

## ----predict------------------------------------------------------------------
predict(fit, rbind(c(0, 1), c(1, -0.6)))

## ----ward---------------------------------------------------------------------
z <- rbind(matrix(rnorm(600), ncol = 2),
           matrix(rnorm(600, mean = 4, sd = 1.4), ncol = 2),
           cbind(rnorm(300, 8), rnorm(300)))
fit3 <- MergeKmeans(z, K = 15, G = 3, linkage = "ward.D", nstart = 25)
plot(fit3, what = "classification", asp = 1)

