---
title: "4. Analysis"
author: "Yuki Atsusaka and Seo-young Silvia Kim"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{4. Analysis}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

```{r, message=FALSE, warning=FALSE}
library(rankingQ)
library(estimatr)
data(identity)
```

The IPW workflow is easiest to think of in two steps. First,
`imprr_weights()` estimates respondent-level correction weights. Those
weights can then be used for point estimation in downstream analyses.

```{r}
out_weights <- imprr_weights(
  identity,
  main_q = c("party", "religion", "gender", "race"),
  anc_correct = "anc_correct_identity"
)

out_weights$est_p_random
```

For example, to estimate the average rank of party as a point estimate,
one can leverage weighted linear regression as follows:

```{r}
lm_robust(
  party ~ 1,
  data = out_weights$results,
  weights = out_weights$results$weights
) |>
  tidy()
```

That gives a valid point estimate, but its standard error treats the
estimated IPW weights as fixed. For built-in ranking summaries, use
`imprr_weights_boot()`, which resamples respondents, reruns
`imprr_weights()` inside each resample, and summarizes the resulting
quantities of interest.

## Computing Average Ranks

The `avg_rank` function remains a convenient way to compute point
estimates from the IPW-adjusted respondent-level data:

```{r}
items_df <- data.frame(
  variable = c("party", "religion", "gender", "race"),
  item = c("Party", "Religion", "Gender", "Race")
)

avg_rank(out_weights$results, items = items_df, weight = "weights", raw = FALSE)
```

For bootstrap uncertainty on the same quantities, `imprr_weights_boot()`
returns summaries in the same general format as `imprr_direct()`:

```{r}
out_boot <- imprr_weights_boot(
  identity,
  main_q = c("party", "religion", "gender", "race"),
  anc_correct = "anc_correct_identity",
  n_bootstrap = 10,
  seed = 123
)

out_boot$est_p_random
subset(out_boot$results, qoi == "average rank")
```

The same object also contains bootstrap summaries for pairwise, top-k,
and marginal ranking quantities:

```{r}
subset(out_boot$results, qoi == "pairwise ranking")
```

If you want uncertainty for an arbitrary downstream weighted analysis,
the same principle applies: resample respondents and rerun
`imprr_weights()` within each resample before recomputing the target
estimand.
