---
title: "Get Started"
description: "A brief introduction to kcmeans."
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Get Started}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

This article is a brief introduction to ``kcmeans``.

```{r}
library(kcmeans)
set.seed(51944)
```

To illustrate ``kcmeans``, consider simulating a small dataset with a continuous outcome variable ``y``, two observed predictors -- a categorical variable ``Z`` and a continuous variable ``X`` -- and an (unobserved) Gaussian error. As in Wiemann (2023), the reduced form has an unobserved lower-dimensional representation dependent on the latent categorical variable ``Z0``.
```{r}
# Sample parameters
nobs = 800 # sample size
# Sample data
X <- rnorm(nobs)
Z <- sample(1:20, nobs, replace = T)
Z0 <- Z %% 4 # lower-dimensional latent categorical variable
y <- Z0 + X + rnorm(nobs)
```


``kcmeans`` is then computed by combining the categorical feature with the continuous feature. By default, the categorical feature is the first column. Alternatively, the column corresponding to the categorical feature can be set via the ``which_is_cat`` argument. Computation is _very_ quick -- indeed the dynamic programming algorithm of the leveraged ``Ckmeans.1d.dp`` package is polynomial in the number of values taken by the categorical feature ``Z``. See also ``?kcmeans`` for details.

```{r}
system.time({
kcmeans_fit <- kcmeans(y = y, X = cbind(Z, X), K = 4)
})
```

We may now use the ``predict.kcmeans`` method to construct fitted values and/or compute predictions of the lower-dimensional latent categorical feature ``Z0``. See also ``?predict.kcmeans`` for details.
```{r}
# Predicted values for the outcome + R^2
y_hat <- predict(kcmeans_fit, cbind(Z, X))
round(1 - mean((y - y_hat)^2) / mean((y - mean(y))^2), 3)

# Predicted values for the latent categorical feature + missclassification rate
Z0_hat <- predict(kcmeans_fit, cbind(Z, X), clusters = T) - 1
mean((Z0 - Z0_hat)!=0)
```

Finally, it is also straightforward to compute standard errors for the final coefficients, e.g., using ``summary.lm``:

```{r}
# Compute the linear regression object and call summary.lm
lm_fit <- lm(y ~ as.factor(Z0_hat) + X)
summary(lm_fit)
```

# References
Wiemann T (2023). "Optimal Categorical Instruments." https://arxiv.org/abs/2311.17021
