---
title: "wtdPropTable"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{wtdPropTable}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
library(coreStatsNMR)
library(dplyr)
# library(data.table)

set.seed(1234)
```

`wtdPropTable` is a function for calculating the propotion of a dataset present in any number of groups, with or without weights. It takes up to 4 input values: a dataframe, two variables for grouping the dataset, and an optional column of weights.

### Sample data

For testing, we use the `mtcars` dataset that comes stock with R. It contains data from the 1974 Motor Trend US magazine, qith fuel economy and other statistics for a set of 32 cars. It looks something like this:

```{r mtcars}
glimpse(mtcars)
```

We add random weights to the data for testing below.

```{r test_data, echo=TRUE}
set.seed(1234)

rand_wt <- data.frame(rand_bin = 1:3,
                      rand_wt = rnorm(3, mean = 1, sd = 0.333))

test_data <- mtcars |> 
  mutate(index = row_number(),
         rand_bin = sample(1:3, nrow(mtcars), replace = TRUE)) |> 
  merge(rand_wt,
        by = "rand_bin")
```

### Changing weights

The code chunk below applies `wtdPropTable` to the test data, comparing proportions when weighting either by horsepower (`hp`) or the random weight variable we created (`rand_wt`). Switching the weighting scheme only changes the weighted overal proportions (in the right column).

```{r wtdProp_0}
wtdPropTable(test_data, x = "cyl", y = "gear", totWeightVar = "hp") |> 
    knitr::kable()

wtdPropTable(test_data, x = "cyl", y = "gear", totWeightVar = "rand_wt") |>
    knitr::kable()
```

```{r wtdProp_1}
wtdPropTable(mtcars, x = "cyl", y = "gear", totWeightVar = "hp", pct_format = FALSE) |> 
    mutate(across(2:5, as.numeric)) |> 
    mutate(across(2:5, ~ifelse(gear == "n", round(.x, 0), round(.x, 2)) |> 
                      as.character())) |> 
    knitr::kable(digits = 2, drop0trailing = TRUE)

wtdPropTable(mtcars, x = "cyl", y = "gear", totWeightVar = "hp", pct_format = TRUE, accuracy = 0.1) |> 
    knitr::kable()

wtdPropTable(mtcars, x = "cyl", y = "gear", totWeightVar = "hp", accuracy = 1) |> 
    knitr::kable()

wtdPropTable(mtcars, x = "cyl", y = "gear", totWeightVar = "hp", tot.label = "Statewide") |> 
    knitr::kable()
```

