The easiest way to understand what’s going on here is to first play around with R Markdown or R Notebooks. spin is a way of integrating code and text the same way R Markdown does, but works better for situations when you have a lot more code than text, and therefore want to use plain R script i.e. .R files rather than .Rmd files.

You may find these links from Dean Attali helpful: general intro to sping and intro to ezknitr

You can compile this script with a number of different ways e.g. using the “compile notebook” button in RStudio. Personally, I like to use the ezspin command from the ezknitr package. This helps to avoid some working directory pains. When I’m ready to compile the script, I’ll run something like the command below in the console:

ezknitr::ezspin("scripts/fake_analysis.R", out_dir = "reports")

Basics

Example “analysis”

A quick example to show how the code and text integrate. The gapminder data is available as a package so you should be able to reproduce this file by just hitting “compile notebook” in RStudio.

library(tidyverse)
library(gapminder)

gapminder
## # A tibble: 1,704 × 6
##        country continent  year lifeExp      pop gdpPercap
##         <fctr>    <fctr> <int>   <dbl>    <int>     <dbl>
## 1  Afghanistan      Asia  1952  28.801  8425333  779.4453
## 2  Afghanistan      Asia  1957  30.332  9240934  820.8530
## 3  Afghanistan      Asia  1962  31.997 10267083  853.1007
## 4  Afghanistan      Asia  1967  34.020 11537966  836.1971
## 5  Afghanistan      Asia  1972  36.088 13079460  739.9811
## 6  Afghanistan      Asia  1977  38.438 14880372  786.1134
## 7  Afghanistan      Asia  1982  39.854 12881816  978.0114
## 8  Afghanistan      Asia  1987  40.822 13867957  852.3959
## 9  Afghanistan      Asia  1992  41.674 16317921  649.3414
## 10 Afghanistan      Asia  1997  41.763 22227415  635.3414
## # ... with 1,694 more rows
ggplot(filter(gapminder, country == "Afghanistan"), aes(year, lifeExp)) + 
  geom_line() + 
  labs(title = "Life Expectancy in Afghanistan increasing since 1950", 
       subtitle = "Slows down around 1990s")