---
title: "Lec 26 - R Packages"
subtitle: "<br/> Statistical Programming"
author: "Sta 323 | Spring 2022"
date: "<br/> Dr. Colin Rundel"
output:
  xaringan::moon_reader:
    css: ["slides.css"]
    lib_dir: libs
    nature:
      highlightStyle: solarized-light
      highlightLines: true
      countIncrementalSlides: false
      ratio: "16:9"
---
exclude: true

```{r, message=FALSE, warning=FALSE, include=FALSE}
options(
  htmltools.dir.version = FALSE, # for blogdown
  width = 80,
  tibble.width = 80
)

knitr::opts_chunk$set(
  fig.align = "center",
  out.width = "80%",
  dpi = 300,
  fig.retina = 2
)

htmltools::tagList(rmarkdown::html_dependency_font_awesome())

options(width=120)
options(tibble.width = 100)
```

---

## What are R packages?

R packages are just a collection of files (R code, compiled code, data, documentation, etc.) that live in your library path.

--

```{r}
.libPaths()
```

--

When you run `library(pkg)` the functions (and objects) in the package's namespace are attached to the global search path.


```{r}
dir(.libPaths())
```

---

## Search path

```{r}
search()
```

--

```{r}
library(diffmatchpatch)
```

--

```{r}
search()
```

---

## Loading vs attaching

If you do not want to attach a package you can directly use functions via `::` or load it with `requireNamespace()`. 

.small[
```{r}
loadedNamespaces()
```
]

--

.small[
```{r}
requireNamespace("forcats")
```
]

--

.small[
```{r}
loadedNamespaces()
search()
```
]

---

## Where to R packages come from

We've already seen the two primary sources of R packages:

CRAN:
```{r eval=FALSE}
install.packages("diffmatchpatch")
```

GitHub:
```{r eval=FALSE}
remotes::install_github("rundel/diffmatchpatch")
```

there is one other method that comes up (particularly around package development), which is to install a package from local files.

Local install:

```{bash eval=FALSE}
R CMD install diffmatchpatch_0.1.0.tar.gz
```

```{r eval=FALSE}
devtools::install("diffmatchpatch_0.1.0.tar.gz")
```

---

## What is CRAN

It is the Comprehensive R Archive Network which is the central repository of R packages.

* Maintained by the R Foundation and run by a team of volunteers, ~22k packages 

* Retains all current versions of released packages as well as archives of previous versions

* Similar in spirit to Perl's CPAN, TeX's CTAN, and Python's PyPI

* Some important features:
  
  * All submissions are reviewed by humans + automated checks
  
  * Strictly enforced submission policies and package requiements
  
  * All packages must be actively maintained and support upstream and downstream changes

.footnote[
See [Writing R Extensions](https://cran.r-project.org/doc/manuals/r-release/R-exts.html)
]

---

## Structure of an R Package

<br/>
<br/>

```{r echo=FALSE}
knitr::include_graphics("imgs/r_pkg_struct.jpeg")
```

.footnote[
From [A Quickstart Guide for Building Your First R Package](https://methodsblog.com/2015/11/30/building-your-first-r-package/)
]

---

## Core components

* `DESCRIPTION` - file containing package metadata (e.g. package name, description, version, license, and author details). Also specifies package dependencies,

* `NAMESPACE` - details which functions and objects are exported by your package

* `R/` - folder containing R script files (`.R`)

* `man/` - folder containing R documentation files (`.Rd`)

--

The following components are optional, but quite common:

* `tests/` - folder contain unit tests

* `src/` - folder containing code to be compiled (usually C / C++)

* `data/` - folder containing example data sets (exported as `.Rdata` via `save()`)

* `inst/` - files that will be copied to the package's top-level directory when it is installed (e.g. examples or data files that don't belong in `data/`)

* `vignettes/` - file implementing long form documentation, can be static (`.pdf` or `.html`) or literate documents (e.g. `.Rmd` or `.Rnw`)

---

## Package contents

.pull-left[
.small[
Source Package
```{r}
fs::dir_tree("~/Desktop/Projects/diffmatchpatch/")
```
] ]

.pull-right[
.small[
Installed Package
```{r}
fs::dir_tree(system.file(package="diffmatchpatch"))
```
] ]


---
class: center, middle

## A deeper dive on [diffmatchpatch](https://github.com/rundel/diffmatchpatch)

---

## Package Installation

```{r echo=FALSE, out.width="80%"}
knitr::include_graphics("imgs/r_pkg_install.png")
```

.footnote[
From [R Packages - Chap. 4](https://r-pkgs.org/package-structure-state.html#installed-package)
]

---

## Package Installion - Files


```{r echo=FALSE, out.width="55%"}
knitr::include_graphics("imgs/r_pkgs_fig.png")
```

.footnote[
From [R Packages - Chap. 4.5](https://r-pkgs.org/package-structure-state.html#bundled-package)
]


---

## Package development

What follows is an *opinionated* introduction to package development, 

* this is not the only way to do thing (none of the following are required)

* I would strongly recommend using:
  * RStudio
  * RStudio projects
  * GitHub
  * usethis
  * roxygen2


---
class: center, middle

```{r echo=FALSE, out.width="45%"}
knitr::include_graphics("imgs/hex_usethis.png")
```

---

## `usethis`

This is an immensely useful package for automating all kinds of routine (and tedious) tasks within R

* Tools for managing git and GitHub configuration

* Tools for managing collaboration on GitHub via pull requests (see `pr_*()`)

* Tools for creating and configuring packages

* Tools for configuring your R environment (e.g. `.Rprofile` and `.Renviron`)

* and much much more

---
class: center, middle

## Live demo - Building a Package
