---
title: "Bootstrap Confidence Intervals for Relative Weights Analysis"
author: "Martin Chan"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Bootstrap Confidence Intervals for Relative Weights Analysis}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "man/figures/README-",
  out.width = "100%",
  error = FALSE,
  warning = FALSE,
  message = FALSE
)
```

```{r setup}
library(rwa)
library(dplyr)
library(ggplot2)
```

## Introduction

Bootstrap confidence intervals represent a major advancement in Relative Weights Analysis, addressing a long-standing methodological limitation. This vignette provides comprehensive guidance on using bootstrap methods with the `rwa` package for statistical significance testing of predictor importance.

## Why Bootstrap for RWA?

### The Statistical Challenge

As noted by Tonidandel et al. (2009):

> "The difficulty in determining the statistical significance of relative weights stems from the fact that the exact (or small sample) sampling distribution of relative weights is unknown."

Traditional RWA provides point estimates of relative importance but lacks a framework for statistical inference. Bootstrap methods solve this by empirically estimating the sampling distribution of relative weights.

### Bootstrap Solution

Bootstrap resampling:
1. **Creates multiple samples** from your original data
2. **Calculates RWA** for each bootstrap sample  
3. **Estimates confidence intervals** from the distribution of bootstrap results
4. **Enables significance testing** by comparing each predictor against a randomly generated variable

### How significance is assessed

A relative weight **cannot be tested against zero**. Raw relative weights are
non-negative, so a predictor with no real relationship to the outcome still
receives a small positive weight, and an interval around that weight will
almost always exclude zero.

Following Tonidandel, LeBreton and Johnson (2009) — who suggest comparing a
weight against that of a randomly generated variable to judge whether it
exceeds what chance alone would produce (see also the discussion in
`vignette("evaluating-rwa-method-reference")`) — significance is instead
assessed by adding a **randomly generated variable** to the model and
bootstrapping the *difference* between each predictor's weight and the random
variable's weight.

The directional cutoff applied by this package is: a predictor is flagged
significant only when the **lower bound** of that difference interval is
above zero, meaning it explains meaningfully more variance than noise would.
An interval lying entirely *below* zero means the predictor performed worse
than the random variable, which is equally not evidence of importance, so it
is not flagged significant either.

This means the package reports two distinct intervals:

| Columns | Purpose |
|---|---|
| `Raw.RelWeight.CI.Lower` / `.Upper` | Descriptive interval around the weight itself. **Not** a significance test. |
| `Random.Diff.CI.Lower` / `.Upper` | Difference from a random variable's weight. `Raw.Significant` is `TRUE` when `Random.Diff.CI.Lower > 0`. |

## Basic Bootstrap Analysis

### Sampling scope

The implementation uses independent, identically distributed (iid)
individual-row resampling. For observation-weighted RWA, each sampled row
carries its original weight; clusters, strata, and replicate-weight survey
designs are not supported. Outcome-missing rows are removed before resampling,
while other missing-data filters are applied within each sample. Invalid
samples stop with an error rather than dropping predictors or retrying.
See `vignette("weighted-missing-data")` for the filtering contract and examples.

### Simple Bootstrap Example

```{r bootstrap-basic}
# Bootstrap analysis with 1000 samples
result_bootstrap <- mtcars %>%
  rwa(outcome = "mpg",
      predictors = c("cyl", "disp", "hp", "gear"),
      bootstrap = TRUE,
      n_bootstrap = 1000,
      conf_level = 0.95)

# View results with confidence intervals
result_bootstrap$result
```

### Understanding Bootstrap Output

The bootstrap analysis enhances the standard RWA output with:

- **Raw.RelWeight.CI.Lower/Upper**: confidence intervals around each raw weight, for description rather than testing
- **Random.Diff.CI.Lower/Upper**: confidence intervals for the difference from a randomly generated variable's weight
- **Raw.Significant**: significance flag, `TRUE` when the random-comparison interval excludes zero

```{r bootstrap-interpretation}
# Bootstrap-specific information
cat("Bootstrap samples used:", result_bootstrap$bootstrap$n_bootstrap, "\n")

# Detailed CI information
print(result_bootstrap$bootstrap$ci_results$raw_weights)

# Identify significant predictors
significant_vars <- result_bootstrap$result %>%
  filter(Raw.Significant == TRUE) %>%
  pull(Variables)

cat("Significant predictors:", paste(significant_vars, collapse = ", "))
```

## Advanced Bootstrap Features

### Comprehensive Bootstrap Analysis

For detailed analysis including focal variable comparisons:

```{r bootstrap-comprehensive}
# Comprehensive bootstrap with focal variable comparison
result_comprehensive <- mtcars %>%
  rwa(outcome = "mpg",
      predictors = c("cyl", "disp", "hp", "gear", "wt"),
      bootstrap = TRUE,
      comprehensive = TRUE,
      focal = "wt",  # Compare other variables to weight
      n_bootstrap = 500)  # Fewer samples for speed

# Access all bootstrap results
names(result_comprehensive$bootstrap$ci_results)
```

### Bootstrap Parameters

Key parameters for bootstrap analysis:

- **`n_bootstrap`**: Number of bootstrap samples (default: 1000)
- **`conf_level`**: Confidence level (default: 0.95)
- **`focal`**: Focal variable for comparative analysis
- **`comprehensive`**: Enable additional bootstrap tests

```{r bootstrap-parameters}
# Example with different parameters
custom_bootstrap <- mtcars %>%
  rwa(outcome = "mpg",
      predictors = c("cyl", "disp"),
      bootstrap = TRUE,
      n_bootstrap = 2000,  # More samples for precision
      conf_level = 0.99)   # 99% confidence intervals

custom_bootstrap$result
```

## Rescaled Weight Confidence Intervals

### Important Considerations

**Rescaled weight confidence intervals should be interpreted with caution** due to compositional data constraints. They are not recommended for formal statistical inference.

```{r rescaled-ci-warning}
# Rescaled CIs (use with caution)
result_rescaled_ci <- mtcars %>%
  rwa(outcome = "mpg",
      predictors = c("cyl", "disp", "hp"),
      bootstrap = TRUE,
      include_rescaled_ci = TRUE,
      n_bootstrap = 500)

# Note the warning message about interpretation
result_rescaled_ci$result
```

### Why Rescaled CIs Are Problematic

Rescaled weights are **compositional data** (they sum to 100%), which creates dependencies between variables. This violates assumptions needed for independent confidence intervals.

**Recommendation**: Focus on **raw weight confidence intervals** for statistical inference.

## Real-World Applications

### Diamond Price Analysis

```{r diamonds-example}
# Analyze diamond price drivers
diamonds_subset <- diamonds %>%
  select(price, carat, depth, table, x, y, z) %>%
  sample_n(1000)  # Sample for faster computation

diamond_rwa <- diamonds_subset %>%
  rwa(outcome = "price",
      predictors = c("carat", "depth", "table", "x", "y", "z"),
      bootstrap = TRUE,
      applysigns = TRUE,
      n_bootstrap = 500)

print(diamond_rwa$result)
```

### Interpreting Results

```{r diamonds-interpretation}
# Focus on significant predictors (results are already sorted by importance)
significant_drivers <- diamond_rwa$result %>%
  filter(Raw.Significant == TRUE) %>%
  select(Variables, Rescaled.RelWeight, Sign.Rescaled.RelWeight)

cat("Significant diamond price drivers (sorted by importance):\n")
print(significant_drivers)

cat("\nModel R-squared:", round(diamond_rwa$rsquare, 3))
```

## Best Practices

### 1. Sample Size Guidelines

```{r sample-size}
# Check your sample size
n_obs <- mtcars %>% 
  select(mpg, cyl, disp, hp, gear) %>% 
  na.omit() %>% 
  nrow()

cat("Sample size:", n_obs)
cat("\nRecommended bootstrap samples:", min(2000, n_obs * 10))

# Rule of thumb: At least 1000 bootstrap samples, more for smaller datasets
```

### 2. Confidence Interval Interpretation

The intervals around the raw weights describe **precision**, not significance.
Use them to judge how tightly each weight is estimated; use `Raw.Significant`
(from the random-variable comparison) to judge importance.

```{r ci-interpretation}
# Examine CI characteristics
ci_data <- result_bootstrap$bootstrap$ci_results$raw_weights
print(head(ci_data))

# Assess precision
ci_analysis <- ci_data %>%
  mutate(
    ci_width = ci_upper - ci_lower,
    precision = case_when(
      ci_width < 0.05 ~ "High precision",
      ci_width < 0.15 ~ "Medium precision", 
      TRUE ~ "Low precision"
    )
  )

print(ci_analysis)
```

### 3. Bootstrap Method Selection

The package automatically selects the best available bootstrap CI method:

1. **BCA (Bias-Corrected and Accelerated)** - Preferred when possible
2. **Percentile** - Fallback if BCA fails
3. **Basic bootstrap** - Final fallback option

```{r bootstrap-methods}
# Check which methods were used
ci_methods <- result_bootstrap$bootstrap$ci_results$raw_weights %>%
  count(ci_method)

print(ci_methods)
```

## Performance Considerations

### Bootstrap Speed Tips

```{r performance-tips}
# For large datasets or many predictors, consider:

# 1. Reduce bootstrap samples for initial exploration
quick_result <- mtcars %>%
  rwa(outcome = "mpg", 
      predictors = c("cyl", "disp"), 
      bootstrap = TRUE, 
      n_bootstrap = 500)  # Faster

# 2. Use comprehensive analysis only when needed
# comprehensive = TRUE adds computational overhead

# 3. Consider parallel processing for very large analyses
# (not currently implemented but could be future enhancement)
```

### Memory Usage

```{r memory-usage}
# Bootstrap objects can be large - access specific components
str(result_bootstrap$bootstrap, max.level = 1)

# For memory efficiency, extract only needed results
ci_summary <- result_bootstrap$bootstrap$ci_results$raw_weights %>%
  select(variable, ci_lower, ci_upper, ci_method)

print(ci_summary)
```

## Troubleshooting

### Common Bootstrap Issues

```{r troubleshooting}
# 1. Check for perfect multicollinearity
cor_check <- mtcars %>%
  select(cyl, disp, hp, gear) %>%
  cor()

# Look for correlations = 1.0 (excluding diagonal)
perfect_cor <- which(abs(cor_check) == 1 & cor_check != diag(diag(cor_check)), arr.ind = TRUE)

if(length(perfect_cor) > 0) {
  cat("Perfect multicollinearity detected - remove redundant variables")
} else {
  cat("No perfect multicollinearity detected")
}

# 2. Ensure adequate sample size
min_sample_size <- 5 * length(c("cyl", "disp", "hp", "gear"))  # 5 obs per predictor
actual_sample_size <- nrow(na.omit(mtcars[c("mpg", "cyl", "disp", "hp", "gear")]))

cat("\nMinimum recommended sample size:", min_sample_size)
cat("\nActual sample size:", actual_sample_size)
```

## Reporting Bootstrap Results

### Standard Reporting Format

When reporting bootstrap RWA results, include:

1. **Sample size** and missing data handling
2. **Bootstrap parameters** (number of samples, confidence level)
3. **CI method** used (BCA, percentile, basic)
4. **Significant predictors** with confidence intervals
5. **Model fit** (R-squared)

### Example Report

```{r reporting-example}
# Generate a summary report
report_data <- result_bootstrap$result %>%
  filter(Raw.Significant == TRUE) %>%
  arrange(desc(Rescaled.RelWeight)) %>%
  select(Variables, Rescaled.RelWeight, Raw.RelWeight.CI.Lower, Raw.RelWeight.CI.Upper)

cat("Relative Weights Analysis Results\n")
cat("=================================\n")
cat("Sample size:", result_bootstrap$n, "\n")
cat("Bootstrap samples:", result_bootstrap$bootstrap$n_bootstrap, "\n")
cat("Model R-squared:", round(result_bootstrap$rsquare, 3), "\n\n")
cat("Significant Predictors:\n")
print(report_data)
```

## References

**Bootstrap Methods in RWA:**

- Tonidandel, S., LeBreton, J. M., & Johnson, J. W. (2009). Determining the statistical significance of relative weights. *Psychological Methods*, 14(4), 387-399.

**General Bootstrap Theory:**

- Efron, B., & Tibshirani, R. J. (1993). *An introduction to the bootstrap*. Chapman & Hall/CRC.

**Compositional Data Analysis:**

- Aitchison, J. (1986). *The statistical analysis of compositional data*. Chapman & Hall.

## Conclusion

Bootstrap confidence intervals provide a robust solution for statistical inference in Relative Weights Analysis. By following the guidelines in this vignette, researchers can:

- Determine statistical significance of predictor importance
- Report confidence intervals with appropriate interpretations  
- Avoid common pitfalls in bootstrap analysis
- Apply best practices for reliable results

The bootstrap functionality in the `rwa` package represents a significant advancement in making RWA a complete tool for both exploratory analysis and confirmatory research.
