---
title: "Using renv with reproducibleRchunks"
author: "Andreas Brandmaier"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Using renv with reproducibleRchunks}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

library(reproducibleRchunks)
```

# Introduction

This vignette demonstrates how to create a small project using
`renv` for dependency management. We will initialize a project,
install the `psych` package, and run a simple factor analysis on
one of the datasets that ships with that package, all while using
`reproducibleRchunks`.

# Creating a project

First, inside your R project, initialize `renv` to track and manage package dependencies:

```{r eval=FALSE}
# Initialize renv
renv::init()
```

`renv` creates a project-specific library and writes a lock file
to record package versions. Your R session will be restarted (if running inside RStudio). 
Next we install the `psych` package as well as the `reproducibleRchunks` in the managed environment:

```{r eval=FALSE}
renv::install("psych")
renv::install("reproducibleRchunks")
```

After installation, snapshot the project state so the lock file is
updated:

```{r eval=FALSE}
renv::snapshot(prompt = FALSE)
```

# Running a factor analysis

With the packages installed and recorded, we can load `psych` and
run a quick factor analysis on the `bfi` dataset that comes with
that package. The following code chunk could now be a part of an R Markdown document inside your project:

```{reproducibleR}
library(psych)

# Use the first 200 cases of the bfi dataset for speed
bfi_subset <- head(bfi, 200)

fa_result <- fa(bfi_subset[, 1:10], nfactors = 3)
fa_result
```

This chunk is executed with `reproducibleR`, so fingerprints of
`bfi_subset` and `fa_result` are stored for later reproducibility
checks.

Note that if you operate inside RStudio, RStudio will ask your permission to install all packages necessary to render Markdown files inside your managed environment. 

# Restoring the environment

If you share your project, others can reproduce the same setup by
calling `renv::restore()` in the project directory. This will
install the recorded package versions and allow them to re-run
the analyses above with verified reproducibility.

```{r eval=FALSE}
renv::restore()
```

# GitHub actions

If you host your project on GitHub, you can add a github action that automatically verifies reproduction in the GitHub cloud:

```{r eval=FALSE}
reproducibleRchunks::use_github_action()
```

Depending on whether reproduction succeeded of failed, a badge is generated and added and committed to your repository. This is how the badges look like depending on the status:

![](https://img.shields.io/badge/reproduced-brightgreen.svg)
 or 
![](https://img.shields.io/badge/reproduction-failed-red.svg)

