---
title: "Latent Variable Measurement Error Correction with `lpmec`"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{lpmec Package Tutorial}
  %\VignetteEngine{knitr::rmarkdown}
  %\usepackage[UTF-8]{inputenc}
---

## Introduction

This tutorial demonstrates how to use the `lpmec` package for measurement error correction in regression models using latent variable estimation. The package implements bootstrapped analyses to account for measurement error in observed indicators and provides corrected regression coefficients.

## Installation

First install the required dependencies and the `lpmec` package:
```{r setup, eval=FALSE}
# Install lpmec from source (replace with appropriate installation method)
# devtools::install_github("cjerzak/lpmec-software", subdir = "lpmec")
```


## Basic Usage

### Data Simulation

Simulate data with a latent predictor and observed binary indicators:

```{r, eval=TRUE}
set.seed(123)
n <- 1000  # Number of observations
d <- 10    # Number of observable indicators

# Generate latent variable and observed outcomes
x_true <- rnorm(n)
Yobs <- 0.4 * x_true + rnorm(n, sd = 0.35)

# Generate binary indicators of latent variable
ObservablesMat <- sapply(1:d, function(j) {
  p <- pnorm(0.5 * x_true + rnorm(n, sd = 0.5))
  rbinom(n, 1, p)
})
```

### Running the Analysis

Use lpmec to estimate corrected coefficients:

```{r, eval=TRUE}
library(lpmec)

# Run bootstrapped analysis
results <- lpmec(
  Y = Yobs,
  observables = as.data.frame(ObservablesMat),
  n_boot = 10,      # Reduced for demonstration
  n_partition = 5,  # Reduced for demonstration
  estimation_method = "em"
)
```

Compare naive and corrected estimates:
```{r, eval=TRUE}
print(results)
summary(results)
```

You can visualize the relationship between split-half estimates:
```{r}
plot(results)
```

## Advanced Features

### Using Different Estimation Methods

The package supports multiple estimation approaches:

```{r, eval=TRUE}
# Bayesian MCMC estimation (requires Python environment setup)
if(FALSE){
mcmc_results <- lpmec(
  Y = Yobs,
  observables = as.data.frame(ObservablesMat),
  estimation_method = "mcmc",
  conda_env = "lpmec"  # Specify your conda environment
)
}
```

## Conclusion

The `lpmec` package provides robust measurement error correction through:

  - Bootstrapped latent variable estimation
  - Multiple correction methods (OLS, IV, Bayesian)
  - Flexible estimation backends (EM, MCMC)

Refer to package documentation for advanced configuration options.
