---
title: "Introduction to cochranSize"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Introduction to cochranSize}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
```

```{r setup}
library(cochranSize)
```

## What is Cochran's formula?

Cochran's formula estimates the minimum sample size needed for a survey to
achieve a given margin of error at a given confidence level:

$$n_0 = \frac{z^2 \, p (1-p)}{e^2}$$

Where:

- `z` is the z-score for the desired confidence level (e.g. 1.96 for 95%)
- `p` is the estimated proportion of the population with the attribute of
  interest (use 0.5 if unknown — the most conservative assumption)
- `e` is the desired margin of error (e.g. 0.05 for +/-5%)

If the population size `N` is known and relatively small, a finite
population correction is applied:

$$n = \frac{n_0}{1 + \frac{n_0 - 1}{N}}$$

## Basic usage

By default, `cochran_sample_size()` uses a 95% confidence level and a 5%
margin of error — but these are only defaults, not fixed assumptions. Every
parameter can be set explicitly:

```{r}
cochran_sample_size(e = 0.05, conf.level = 0.95)
```

## Known finite population

```{r}
cochran_sample_size(N = 2000, e = 0.05, conf.level = 0.95)
```

## Custom confidence level, margin of error, and expected proportion

```{r}
cochran_sample_size(N = 500, p = 0.3, e = 0.03, conf.level = 0.99)
```

## Using the underlying functions directly

```{r}
n0 <- cochran_n(p = 0.5, e = 0.05, conf.level = 0.95)
n0
cochran_n_adj(n0, N = 1000)
```

## Comparing confidence levels and margins of error

```{r}
settings <- expand.grid(
  conf.level = c(0.90, 0.95, 0.99),
  e = c(0.05, 0.03, 0.01)
)
settings$n0 <- mapply(cochran_n, e = settings$e, conf.level = settings$conf.level)
settings$n0 <- ceiling(settings$n0)
settings[order(settings$conf.level, -settings$e), ]
```

As the table shows, tightening the margin of error or raising the
confidence level both increase the required sample size — margin of error
has the larger effect, since it is squared in the denominator.
