Hands-on Activity 2 - Theory

Stéphane Tuffier

2024-06-05

Plan

  1. Functional programming with purrr
  2. Report generation with Quarto
  3. Table creation with gt
  4. Bonus: Git branch and remote repo

Functional Programming in R with purrr

Functions can be easily applied to multiple elements using functional functions: special functions that uses another function as one of its arguments.

purrr:

  • Part of the tidyverse
  • Focus on functional programming
  • Simplify complex data manipulations

Functional Programming in R with purrr

  • The map family of functions: works by taking a vector (or list), applying a function to each of those items, and outputting the results from each function call.

Functional Programming in R with purrr

paste_text <- function(x) { 
  paste(x, "seconds have passed")
}
purrr::map(1:5, paste_text)
[[1]]
[1] "1 seconds have passed"

[[2]]
[1] "2 seconds have passed"

[[3]]
[1] "3 seconds have passed"

[[4]]
[1] "4 seconds have passed"

[[5]]
[1] "5 seconds have passed"

Functional Programming in R with purrr

Benefits of Using purrr

  • Reduces redundancy
    • Write less code by avoiding repetitive loops
  • Increases code readability
    • Clear and concise syntax
  • Easier to update and debug

Dynamic Report with Quarto

What is Quarto?

  • Open-source scientific publishing system

  • Supports R and Python

  • Integrates code, text, and outputs in one document (HTML, DOCX)

Quarto by Allison Horst

Quarto Document Structure

  ---
  title: "Descriptive Statistics Report"
  author: "Your Name"
  format: html # or docx 
  ---
  
  # Results
  
  ```{r}
library(purrr)
numeric_vars <- c("creatinine", "lead", "barium", "cadmium")
descriptive_stats <- map(numeric_vars, ~ compute_numeric_summaries(nh2007[[.x]]))
descriptive_stats
```
  

Markdown

Text formatting:

  • **bold**,
  • _italic_,
  • # Headers 1,
  • ## Headers 2

Lists:

  • Unordered lists with - or *

  • Ordered lists with 1.

R Code chunks:

```{r}
summary(cars)
```

Table creation with gt

Create publication ready tables in R directly from your data.

There is many functions to style and format tables to match your needs:

  • Automatic number formating
  • Nice labels with special characters
  • Table header spanner
  • Cells highlight

Tables can be exported in many format including html or MS Word.

Table creation with gt

Bonus: Git branching

Basic Git Workflow:

  • Create a branch: git branch new-branch-name
  • Switch to new branch: git checkout new-branch-name
  • Commit changes: git add ., git commit -m "message"
  • Merge branch: git checkout main, git merge new-branch-name

Bonus: Git local and remote