diff --git a/_freeze/schedule/slides/00-r-review/execute-results/html.json b/_freeze/schedule/slides/00-r-review/execute-results/html.json
index 3eb812a..990a648 100644
--- a/_freeze/schedule/slides/00-r-review/execute-results/html.json
+++ b/_freeze/schedule/slides/00-r-review/execute-results/html.json
@@ -1,7 +1,8 @@
{
- "hash": "86d9e3f58e1e8414feba1c2862895ab7",
+ "hash": "a5b1ec29601a86ac60d92a3d9b22b91d",
"result": {
- "markdown": "---\nlecture: \"00 R, Rmarkdown, code, and `{tidyverse}`: A whirlwind tour\"\nformat: revealjs\nmetadata-files: \n - _metadata.yml\n---\n---\n---\n\n## {{< meta lecture >}} {.large background-image=\"gfx/smooths.svg\" background-opacity=\"0.3\"}\n\n[Stat 406]{.secondary}\n\n[{{< meta author >}}]{.secondary}\n\nLast modified -- 11 September 2023\n\n\n\n$$\n\\DeclareMathOperator*{\\argmin}{argmin}\n\\DeclareMathOperator*{\\argmax}{argmax}\n\\DeclareMathOperator*{\\minimize}{minimize}\n\\DeclareMathOperator*{\\maximize}{maximize}\n\\DeclareMathOperator*{\\find}{find}\n\\DeclareMathOperator{\\st}{subject\\,\\,to}\n\\newcommand{\\E}{E}\n\\newcommand{\\Expect}[1]{\\E\\left[ #1 \\right]}\n\\newcommand{\\Var}[1]{\\mathrm{Var}\\left[ #1 \\right]}\n\\newcommand{\\Cov}[2]{\\mathrm{Cov}\\left[#1,\\ #2\\right]}\n\\newcommand{\\given}{\\ \\vert\\ }\n\\newcommand{\\X}{\\mathbf{X}}\n\\newcommand{\\x}{\\mathbf{x}}\n\\newcommand{\\y}{\\mathbf{y}}\n\\newcommand{\\P}{\\mathcal{P}}\n\\newcommand{\\R}{\\mathbb{R}}\n\\newcommand{\\norm}[1]{\\left\\lVert #1 \\right\\rVert}\n\\newcommand{\\snorm}[1]{\\lVert #1 \\rVert}\n$$\n\n\n\n\n\n# The basics\n\n\n## Tour of Rstudio\n\nThings to note\n\n1. Console\n1. Terminal\n1. Scripts, .Rmd, Knit\n1. Files, Projects\n1. Getting help\n1. Environment, Git\n\n\n\n## Simple stuff\n\n:::: {.columns}\n::: {.column width=\"45%\"}\n\n### Vectors:\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nx <- c(1, 3, 4)\nx[1]\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 1\n```\n:::\n\n```{.r .cell-code}\nx[-1]\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 3 4\n```\n:::\n\n```{.r .cell-code}\nrev(x)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 4 3 1\n```\n:::\n\n```{.r .cell-code}\nc(x, x)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 1 3 4 1 3 4\n```\n:::\n:::\n\n:::\n\n::: {.column width=\"10%\"}\n:::\n\n::: {.column width=\"45%\"}\n\n### Matrices:\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nx <- matrix(1:25, nrow = 5, ncol = 5)\nx[1,]\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 1 6 11 16 21\n```\n:::\n\n```{.r .cell-code}\nx[,-1]\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n [,1] [,2] [,3] [,4]\n[1,] 6 11 16 21\n[2,] 7 12 17 22\n[3,] 8 13 18 23\n[4,] 9 14 19 24\n[5,] 10 15 20 25\n```\n:::\n\n```{.r .cell-code}\nx[c(1,3), 2:3]\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n [,1] [,2]\n[1,] 6 11\n[2,] 8 13\n```\n:::\n:::\n\n\n:::\n::::\n\n\n## Simple stuff\n\n::: flex\n::: w-50\n\n### Lists\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\n(l <- list(\n a = letters[1:2], \n b = 1:4, \n c = list(a = 1)))\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n$a\n[1] \"a\" \"b\"\n\n$b\n[1] 1 2 3 4\n\n$c\n$c$a\n[1] 1\n```\n:::\n\n```{.r .cell-code}\nl$a\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] \"a\" \"b\"\n```\n:::\n\n```{.r .cell-code}\nl$c$a\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 1\n```\n:::\n\n```{.r .cell-code}\nl[\"b\"] # compare to l[[\"b\"]] == l$b\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n$b\n[1] 1 2 3 4\n```\n:::\n:::\n\n:::\n\n\n::: w-50\n\n### Data frames\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\n(dat <- data.frame(\n z = 1:5, \n b = 6:10, \n c = letters[1:5]))\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n z b c\n1 1 6 a\n2 2 7 b\n3 3 8 c\n4 4 9 d\n5 5 10 e\n```\n:::\n\n```{.r .cell-code}\nclass(dat)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] \"data.frame\"\n```\n:::\n\n```{.r .cell-code}\ndat$b\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 6 7 8 9 10\n```\n:::\n\n```{.r .cell-code}\ndat[1,]\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n z b c\n1 1 6 a\n```\n:::\n:::\n\n\n:::\n:::\n\n[Data frames are sort-of lists and sort-of matrices]{.secondary}\n\n\n## Tibbles\n\n[These are `{tidyverse}` data frames]{.secondary}\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\n(dat2 <- tibble(z = 1:5, b = z + 5, c = letters[z]))\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n# A tibble: 5 Ć 3\n z b c \n \n1 1 6 a \n2 2 7 b \n3 3 8 c \n4 4 9 d \n5 5 10 e \n```\n:::\n\n```{.r .cell-code}\nclass(dat2)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] \"tbl_df\" \"tbl\" \"data.frame\"\n```\n:::\n:::\n\n\nWe'll return to classes in a moment. A `tbl_df` is a \"subclass\" of `data.frame`.\n\nAnything that `data.frame` can do, `tbl_df` can do (better).\n\nFor instance, the printing is more informative.\n\nAlso, you can construct one by referencing previously constructed columns.\n\n\n\n# Functions\n\n\n\n## Understanding signatures\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code code-fold=\"true\"}\nsig <- sig::sig\n```\n:::\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nsig(lm)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\nfn <- function(formula, data, subset, weights, na.action, method = \"qr\", model\n = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, contrasts =\n NULL, offset, ...)\n```\n:::\n\n```{.r .cell-code}\nsig(`+`)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\nfn <- function(e1, e2)\n```\n:::\n\n```{.r .cell-code}\nsig(dplyr::filter)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\nfn <- function(.data, ..., .by = NULL, .preserve = FALSE)\n```\n:::\n\n```{.r .cell-code}\nsig(stats::filter)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\nfn <- function(x, filter, method = c(\"convolution\", \"recursive\"), sides = 2,\n circular = FALSE, init = NULL)\n```\n:::\n\n```{.r .cell-code}\nsig(rnorm)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\nfn <- function(n, mean = 0, sd = 1)\n```\n:::\n:::\n\n\n\n## These are all the same\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nset.seed(12345)\nrnorm(3)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 0.5855288 0.7094660 -0.1093033\n```\n:::\n\n```{.r .cell-code}\nset.seed(12345)\nrnorm(n = 3, mean = 0)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 0.5855288 0.7094660 -0.1093033\n```\n:::\n\n```{.r .cell-code}\nset.seed(12345)\nrnorm(3, 0, 1)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 0.5855288 0.7094660 -0.1093033\n```\n:::\n\n```{.r .cell-code}\nset.seed(12345)\nrnorm(sd = 1, n = 3, mean = 0)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 0.5855288 0.7094660 -0.1093033\n```\n:::\n:::\n\n\n* Functions can have default values.\n* You may, but don't have to, name the arguments\n* If you name them, you can pass them out of order (but you shouldn't).\n\n\n## Write lots of functions. I can't emphasize this enough.\n\n::: flex\n\n::: w-50\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nf <- function(arg1, arg2, arg3 = 12, ...) {\n stuff <- arg1 * arg3\n stuff2 <- stuff + arg2\n plot(arg1, stuff2, ...)\n return(stuff2)\n}\nx <- rnorm(100)\n```\n:::\n\n:::\n\n\n::: w-50\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\ny1 <- f(x, 3, 15, col = 4, pch = 19)\n```\n\n::: {.cell-output-display}\n![](00-r-review_files/figure-revealjs/plot-it-1.svg){fig-align='center'}\n:::\n\n```{.r .cell-code}\nstr(y1)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n num [1:100] -3.8 12.09 -24.27 12.45 -1.14 ...\n```\n:::\n:::\n\n\n:::\n:::\n\n\n## Outputs vs. Side effects\n\n::: flex\n::: w-50\n* Side effects are things a function does, outputs can be assigned to variables\n* A good example is the `hist` function\n* You have probably only seen the side effect which is to plot the histogram\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nmy_histogram <- hist(rnorm(1000))\n```\n\n::: {.cell-output-display}\n![](00-r-review_files/figure-revealjs/unnamed-chunk-9-1.svg){fig-align='center'}\n:::\n:::\n\n\n:::\n\n\n::: w-50\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nstr(my_histogram)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\nList of 6\n $ breaks : num [1:14] -3 -2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5 ...\n $ counts : int [1:13] 4 21 41 89 142 200 193 170 74 38 ...\n $ density : num [1:13] 0.008 0.042 0.082 0.178 0.284 0.4 0.386 0.34 0.148 0.076 ...\n $ mids : num [1:13] -2.75 -2.25 -1.75 -1.25 -0.75 -0.25 0.25 0.75 1.25 1.75 ...\n $ xname : chr \"rnorm(1000)\"\n $ equidist: logi TRUE\n - attr(*, \"class\")= chr \"histogram\"\n```\n:::\n\n```{.r .cell-code}\nclass(my_histogram)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] \"histogram\"\n```\n:::\n:::\n\n\n:::\n:::\n\n\n\n## When writing functions, program defensively, ensure behaviour\n\n::: flex\n::: w-50\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nincrementer <- function(x, inc_by = 1) {\n x + 1\n}\n \nincrementer(2)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 3\n```\n:::\n\n```{.r .cell-code}\nincrementer(1:4)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 2 3 4 5\n```\n:::\n\n```{.r .cell-code}\nincrementer(\"a\")\n```\n\n::: {.cell-output .cell-output-error}\n```\nError in x + 1: non-numeric argument to binary operator\n```\n:::\n:::\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nincrementer <- function(x, inc_by = 1) {\n stopifnot(is.numeric(x))\n return(x + 1)\n}\nincrementer(\"a\")\n```\n\n::: {.cell-output .cell-output-error}\n```\nError in incrementer(\"a\"): is.numeric(x) is not TRUE\n```\n:::\n:::\n\n\n:::\n\n\n::: w-50\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nincrementer <- function(x, inc_by = 1) {\n if (!is.numeric(x)) {\n stop(\"`x` must be numeric\")\n }\n x + 1\n}\nincrementer(\"a\")\n```\n\n::: {.cell-output .cell-output-error}\n```\nError in incrementer(\"a\"): `x` must be numeric\n```\n:::\n\n```{.r .cell-code}\nincrementer(2, -3) ## oops!\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 3\n```\n:::\n\n```{.r .cell-code}\nincrementer <- function(x, inc_by = 1) {\n if (!is.numeric(x)) {\n stop(\"`x` must be numeric\")\n }\n x + inc_by\n}\nincrementer(2, -3)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] -1\n```\n:::\n:::\n\n:::\n:::\n\n\n## How to keep track\n\n::: flex\n::: w-50\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nlibrary(testthat)\nincrementer <- function(x, inc_by = 1) {\n if (!is.numeric(x)) {\n stop(\"`x` must be numeric\")\n }\n if (!is.numeric(inc_by)) {\n stop(\"`inc_by` must be numeric\")\n }\n x + inc_by\n}\nexpect_error(incrementer(\"a\"))\nexpect_equal(incrementer(1:3), 2:4)\nexpect_equal(incrementer(2, -3), -1)\nexpect_error(incrementer(1, \"b\"))\nexpect_identical(incrementer(1:3), 2:4)\n```\n\n::: {.cell-output .cell-output-error}\n```\nError: incrementer(1:3) not identical to 2:4.\nObjects equal but not identical\n```\n:::\n:::\n\n:::\n\n\n::: w-50\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nis.integer(2:4)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] TRUE\n```\n:::\n\n```{.r .cell-code}\nis.integer(incrementer(1:3))\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] FALSE\n```\n:::\n\n```{.r .cell-code}\nexpect_identical(incrementer(1:3, 1L), 2:4)\n```\n:::\n\n:::\n:::\n\n. . .\n\n::: callout-important\nIf you copy something, write a function.\n\nValidate your arguments.\n\nTo ensure proper functionality, write tests to check if inputs result in predicted outputs.\n:::\n\n\n\n# Classes and methods\n\n\n\n## Classes\n\n::: flex\n::: w-50\n\nWe saw some of these earlier:\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\ntib <- tibble(\n x1 = rnorm(100), \n x2 = rnorm(100), \n y = x1 + 2 * x2 + rnorm(100)\n)\nmdl <- lm(y ~ ., data = tib )\nclass(tib)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] \"tbl_df\" \"tbl\" \"data.frame\"\n```\n:::\n\n```{.r .cell-code}\nclass(mdl)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] \"lm\"\n```\n:::\n:::\n\n\nThe class allows for the use of \"methods\"\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nprint(mdl)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n\nCall:\nlm(formula = y ~ ., data = tib)\n\nCoefficients:\n(Intercept) x1 x2 \n -0.1742 1.0454 2.0470 \n```\n:::\n:::\n\n\n:::\n\n\n::: w-50\n\n\n* `R` \"knows what to do\" when you `print()` an object of class `\"lm\"`.\n\n* `print()` is called a \"generic\" function. \n\n* You can create \"methods\" that get dispatched.\n\n* For any generic, `R` looks for a method for the class.\n\n* If available, it calls that function.\n\n:::\n:::\n\n## Viewing the dispatch chain\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nsloop::s3_dispatch(print(incrementer))\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n=> print.function\n * print.default\n```\n:::\n\n```{.r .cell-code}\nsloop::s3_dispatch(print(tib))\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n print.tbl_df\n=> print.tbl\n * print.data.frame\n * print.default\n```\n:::\n\n```{.r .cell-code}\nsloop::s3_dispatch(print(mdl))\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n=> print.lm\n * print.default\n```\n:::\n:::\n\n\n\n## R-Geeky But Important\n\nThere are [lots]{.secondary} of generic functions in `R`\n\nCommon ones are `print()`, `summary()`, and `plot()`.\n\nAlso, lots of important statistical modelling concepts:\n`residuals()` `coef()` \n\n(In `python`, these work the opposite way: `obj.residuals`. The dot after the object accesses methods defined for that type of object. But the dispatch behaviour is less robust.) \n\n* The convention is\nthat the specialized function is named `method.class()`, e.g., `summary.lm()`.\n\n* If no specialized function is defined, R will try to use `method.default()`.\n\nFor this reason, `R` programmers try to avoid `.` in names of functions or objects.\n\n\n## Wherefore methods?\n\n\n* The advantage is that you don't have to learn a totally\nnew syntax to grab residuals or plot things\n\n* You just use `residuals(mdl)` whether `mdl` has class `lm`\ncould have been done two centuries ago, or a Batrachian Emphasis Machine\nwhich won't be invented for another five years. \n\n* The one draw-back is the help pages for the generic methods tend\nto be pretty vague\n\n* Compare `?summary` with `?summary.lm`. \n\n\n\n# Environments \n\n\n## Different environments\n\n* These are often tricky, but are very common.\n\n* Most programming languages have this concept in one way or another.\n\n* In `R` code run in the Console produces objects in the \"Global environment\"\n\n* You can see what you create in the \"Environment\" tab.\n\n* But there's lots of other stuff.\n\n* Many packages are automatically loaded at startup, so you have access to the functions and data inside\n\nFor example `mean()`, `lm()`, `plot()`, `iris` (technically `iris` is lazy-loaded, meaning it's not in memory until you call it, but it is available)\n\n\n\n##\n\n* Other packages require you to load them with `library(pkg)` before their functions are available.\n\n* But, you can call those functions by prefixing the package name `ggplot2::ggplot()`.\n\n* You can also access functions that the package developer didn't \"export\" for use with `:::` like `dplyr:::as_across_fn_call()`\n\n::: {.notes}\n\nThat is all about accessing \"objects in package environments\"\n\n:::\n\n\n## Other issues with environments\n\n\nAs one might expect, functions create an environment inside the function.\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nz <- 1\nfun <- function(x) {\n z <- x\n print(z)\n invisible(z)\n}\nfun(14)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 14\n```\n:::\n:::\n\n\nNon-trivial cases are `data-masking` environments.\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\ntib <- tibble(x1 = rnorm(100), x2 = rnorm(100), y = x1 + 2 * x2)\nmdl <- lm(y ~ x2, data = tib)\nx2\n```\n\n::: {.cell-output .cell-output-error}\n```\nError in eval(expr, envir, enclos): object 'x2' not found\n```\n:::\n:::\n\n\n* `lm()` looks \"inside\" the `tib` to find `y` and `x2`\n* The data variables are added to the `lm()` environment\n\n\n## Other issues with environments\n\n[When Knit, `.Rmd` files run in their OWN environment.]{.fourth-colour}\n\nThey are run from top to bottom, with code chunks depending on previous\n\nThis makes them reproducible.\n\nJupyter notebooks don't do this. š±\n\nObjects in your local environment are not available in the `.Rmd`\n\nObjects in the `.Rmd` are not available locally.\n\n::: {.callout-tip}\nThe most frequent error I see is:\n\n* running chunks individually, 1-by-1, and it works\n* Knitting, and it fails\n\nThe reason is almost always that the chunks refer to objects in the Environment that don't exist in the `.Rmd`\n:::\n\n##\n\n\n### This error also happens because:\n\n* `library()` calls were made globally but not in the `.Rmd` \n * so the packages aren't loaded\n\n* paths to data or other objects are not relative to the `.Rmd` in your file system \n * they must be\n\n\n* Carefully keeping Labs / Assignments in their current location will help to avoid some of these.\n\n\n# Debugging\n\n\n\n## How to fix code\n\n* If you're using a function in a package, start with `?function` to see the help\n * Make sure you're calling the function correctly.\n * Try running the examples.\n * paste the error into Google (if you share the error on Slack, I often do this first)\n * Go to the package website if it exists, and browse around\n \n* If your `.Rmd` won't Knit\n * Did you make the mistake on the last slide?\n * Did it Knit before? Then the bug is in whatever you added.\n * Did you never Knit it? Why not?\n * Call `rstudioapi::restartSession()`, then run the Chunks 1-by-1\n \n##\n \nAdding `browser()`\n\n* Only useful with your own functions.\n* Open the script with the function, and add `browser()` to the code somewhere\n* Then call your function.\n* The execution will Stop where you added `browser()` and you'll have access to the local environment to play around\n\n\n## Reproducible examples\n\n::: {.callout-tip}\n## Question I get on Slack that I hate:\n\n\"I ran the code like you had on Slide 39, but it didn't work.\"\n:::\n\n* If you want to ask me why the code doesn't work, you need to show me what's wrong.\n\n::: {.callout-warning}\n## Don't just paste a screenshot!\n\nUnless you get lucky, I won't be able to figure it out from that. And we'll both get frustrated.\n:::\n\nWhat you need is a Reproducible Example or `reprex`.\n\n* This is a small chunk of code that \n 1. runs in it's own environment \n 1. and produces the error.\n \n#\n\nThe best way to do this is with the `{reprex}` package.\n\n\n## Reproducible examples, How it works {.smaller}\n\n1. Open a new `.R` script.\n\n1. Paste your buggy code in the file (no need to save)\n\n1. Edit your code to make sure it's \"enough to produce the error\" and nothing more. (By rerunning the code a few times.)\n\n1. Copy your code.\n\n1. Call `reprex::reprex(venue = \"r\")` from the console. This will run your code in a new environment and show the result in the Viewer tab. Does it create the error you expect?\n\n1. If it creates other errors, that may be the problem. You may fix the bug on your own!\n\n1. If it doesn't have errors, then your global environment is Farblunget.\n\n1. The Output is now on your clipboard. Go to Slack and paste it in a message. Then press `Cmd+Shift+Enter` (on Mac) or `Ctrl+Shift+Enter` (Windows/Linux). Under Type, select `R`.\n\n1. Send the message, perhaps with more description and an SOS emoji.\n\n::: {.callout-note}\nBecause Reprex runs in it's own environment, it doesn't have access to any of the libraries you loaded or the stuff in your global environment. You'll have to load these things in the script.\n:::\n\n\n# Understanding `{tidyverse}`\n\n\n## `{tidyverse}` is huge\n\nCore tidyverse is nearly 30 different R packages, but we're going to just talk about a few of them.\n\nFalls roughly into a few categories:\n\n1. [Convenience functions:]{.secondary} `{magrittr}` and many many others.\n1. [Data processing:]{.secondary} `{dplyr}` and many others.\n1. [Graphing:]{.secondary} `{ggplot2}` and some others like `{scales}`.\n1. [Utilities]{.secondary}\n\n\n. . .\n\n\n\nWe're going to talk quickly about some of it, but ignore much of 2.\n\nThere's a lot that's great about these packages, especially ease of data processing.\n\nBut it doesn't always jive with base `R` (it's almost a separate proglang at this point).\n\n\n## Piping\n\nThis was introduced by `{magrittr}` as `%>%`, \n\nbut is now in base R (>=4.1.0) as `|>`.\n\nNote: there are other pipes in `{magrittr}` (e.g. `%$%` and `%T%`) but I've never used them.\n\nI've used the old version for so long, that it's hard for me to adopt the new one.\n\nThe point of the pipe is to [logically sequence nested operations]{.secondary}\n\n## Example\n\n:::: {.columns}\n::: {.column width=\"50%\"}\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nmse1 <- print(\n sum(\n residuals(\n lm(y~., data = mutate(\n tib, \n x3 = x1^2,\n x4 = log(x2 + abs(min(x2)) + 1)\n )\n )\n )^2\n )\n)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 6.469568e-29\n```\n:::\n:::\n\n\n:::\n\n\n::: {.column width=\"50%\"}\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code code-line-numbers=\"|5-6\"}\nmse2 <- tib |>\n mutate(\n x3 = x1^2, \n x4 = log(x2 + abs(min(x2)) + 1)\n ) %>% # base pipe only goes to first arg\n lm(y ~ ., data = .) |> # note the use of `.`\n residuals() |>\n magrittr::raise_to_power(2) |> # same as `^`(2)\n sum() |>\n print()\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 6.469568e-29\n```\n:::\n:::\n\n\n:::\n::::\n\n## \n\nIt may seem like we should push this all the way\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code code-line-numbers=\"|9-10\"}\ntib |>\n mutate(\n x3 = x1^2, \n x4 = log(x2 + abs(min(x2)) + 1)\n ) %>% # base pipe only goes to first arg\n lm(y ~ ., data = .) |> # note the use of `.`\n residuals() |>\n magrittr::raise_to_power(2) |> # same as `^`(2)\n sum() ->\n mse3\n```\n:::\n\n\nThis works, but it's really annoying.\n\n## A new one...\n\nJust last week, I learned\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nlibrary(magrittr)\ntib <- tibble(x = 1:5, z = 6:10)\ntib <- tib |> mutate(b = x + z)\ntib\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n# A tibble: 5 Ć 3\n x z b\n \n1 1 6 7\n2 2 7 9\n3 3 8 11\n4 4 9 13\n5 5 10 15\n```\n:::\n\n```{.r .cell-code}\n# start over\ntib <- tibble(x = 1:5, z = 6:10)\ntib %<>% mutate(b = x + z)\ntib\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n# A tibble: 5 Ć 3\n x z b\n \n1 1 6 7\n2 2 7 9\n3 3 8 11\n4 4 9 13\n5 5 10 15\n```\n:::\n:::\n\n\n\n\n## Data processing in `{dplyr}` {.smaller}\n\nThis package has all sorts of things. And it interacts with `{tibble}` generally.\n\nThe basic idea is \"tibble in, tibble out\".\n\nSatisfies [data masking]{.secondary} which means you can refer to columns by name or use helpers like `ends_with(\"_rate\")`\n\nMajorly useful operations:\n\n1. `select()` (chooses columns to keep)\n1. `mutate()` (showed this already)\n1. `group_by()`\n1. `pivot_longer()` and `pivot_wider()`\n1. `left_join()` and `full_join()`\n1. `summarise()`\n\n::: {.callout-note}\n`filter()` and `select()` are functions in Base R. \n\nSometimes you get š because it called the wrong version. \n\nTo be sure, prefix it like `dplyr::select()`.\n:::\n\n## A useful data frame\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nlibrary(epidatr)\ncovid <- covidcast(\n source = \"jhu-csse\",\n signals = \"confirmed_7dav_incidence_prop,deaths_7dav_incidence_prop\",\n time_type = \"day\",\n geo_type = \"state\",\n time_values = epirange(20220801, 20220821),\n geo_values = \"ca,wa\") |>\n fetch() |>\n select(geo_value, time_value, signal, value)\n\ncovid\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n# A tibble: 84 Ć 4\n geo_value time_value signal value\n \n 1 ca 2022-08-01 confirmed_7dav_incidence_prop 45.4\n 2 wa 2022-08-01 confirmed_7dav_incidence_prop 27.7\n 3 ca 2022-08-02 confirmed_7dav_incidence_prop 44.9\n 4 wa 2022-08-02 confirmed_7dav_incidence_prop 27.7\n 5 ca 2022-08-03 confirmed_7dav_incidence_prop 44.5\n 6 wa 2022-08-03 confirmed_7dav_incidence_prop 26.6\n 7 ca 2022-08-04 confirmed_7dav_incidence_prop 42.3\n 8 wa 2022-08-04 confirmed_7dav_incidence_prop 26.6\n 9 ca 2022-08-05 confirmed_7dav_incidence_prop 40.7\n10 wa 2022-08-05 confirmed_7dav_incidence_prop 34.6\n# ā¹ 74 more rows\n```\n:::\n:::\n\n\n## Examples\n\nRename the `signal` to something short.\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\ncovid <- covid |> \n mutate(signal = case_when(\n str_starts(signal, \"confirmed\") ~ \"case_rate\", \n TRUE ~ \"death_rate\"\n ))\n```\n:::\n\n\n\nSort by `time_value` then `geo_value`\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\ncovid <- covid |> arrange(time_value, geo_value)\n```\n:::\n\n\nCalculate grouped medians\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\ncovid |> \n group_by(geo_value, signal) |>\n summarise(med = median(value), .groups = \"drop\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n# A tibble: 4 Ć 3\n geo_value signal med\n \n1 ca case_rate 33.2 \n2 ca death_rate 0.112\n3 wa case_rate 23.2 \n4 wa death_rate 0.178\n```\n:::\n:::\n\n\n## Examples\n\nSplit the data into two tibbles by signal\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\ncases <- covid |> \n filter(signal == \"case_rate\") |>\n rename(case_rate = value) |> select(-signal)\ndeaths <- covid |> \n filter(signal == \"death_rate\") |>\n rename(death_rate = value) |> select(-signal)\n```\n:::\n\n\nJoin them together\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\njoined <- full_join(cases, deaths, by = c(\"geo_value\", \"time_value\"))\n```\n:::\n\n\nDo the same thing by pivoting\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\ncovid |> pivot_wider(names_from = signal, values_from = value)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n# A tibble: 42 Ć 4\n geo_value time_value case_rate death_rate\n \n 1 ca 2022-08-01 45.4 0.105\n 2 wa 2022-08-01 27.7 0.169\n 3 ca 2022-08-02 44.9 0.106\n 4 wa 2022-08-02 27.7 0.169\n 5 ca 2022-08-03 44.5 0.107\n 6 wa 2022-08-03 26.6 0.173\n 7 ca 2022-08-04 42.3 0.112\n 8 wa 2022-08-04 26.6 0.173\n 9 ca 2022-08-05 40.7 0.116\n10 wa 2022-08-05 34.6 0.225\n# ā¹ 32 more rows\n```\n:::\n:::\n\n\n\n\n## Plotting with `{ggplot2}`\n\n* Everything you can do with `ggplot()`, you can do with `plot()`. But the \ndefaults are _much_ prettier.\n\n* It's also much easier to adjust by aesthetics / panels by factors.\n\n* It also uses \"data masking\": data goes into `ggplot(data = mydata)`, then the columns are available to the rest.\n\n* It (sort of) pipes, but by adding [layers]{.secondary} with `+`\n\n* It [strongly prefers]{.secondary} \"long\" data frames over \"wide\" data frames.\n\n\n\nI'll give a very fast overview of some confusing bits.\n\n# \n\nI suggest exploring\n\nš [This slide deck](https://djnavarro.net/slides-starting-ggplot/)\n\nfor more help\n\n\n\n---\n\n\n\n::: {.cell layout-align=\"center\" output-location='column'}\n\n```{.r .cell-code}\nggplot(\n data = covid |> \n filter(signal == \"case_rate\")\n) +\n geom_point(\n mapping = aes(\n x = time_value,\n y = value\n )\n ) + \n geom_smooth( \n mapping = aes( \n x = time_value, \n y = value \n ) \n ) \n```\n\n::: {.cell-output-display}\n![](00-r-review_files/figure-revealjs/adding-geoms-1.svg){fig-align='center'}\n:::\n:::\n\n\n\n\n::: {.notes}\n\n* The complete code\n* Data is specified in the ggplot, passed along\n* (we show only case_rate)\n\n\n* The Grey SE shading is pretty ugly\n* And there are two states mashed together\n* That trend is awfully wiggly\n\n:::\n\n---\n\n\n\n::: {.cell layout-align=\"center\" output-location='column'}\n\n```{.r .cell-code}\nggplot(\n data = covid |> filter(signal == \"case_rate\")\n) +\n geom_point(\n mapping = aes(\n x = time_value,\n y = value,\n colour = geo_value\n )\n ) + \n geom_smooth( \n mapping = aes( \n x = time_value, \n y = value,\n colour = geo_value\n ),\n se = FALSE,\n method = \"lm\"\n ) \n```\n\n::: {.cell-output-display}\n![](00-r-review_files/figure-revealjs/adding-geoms2-1.svg){fig-align='center'}\n:::\n:::\n\n\n::: {.notes}\n\n* Separate out the states by colour\n* straight lines instead\n* no more grey shading\n* Why do I keep writing all that mapping = stuff?\n\n:::\n\n---\n\n\n\n::: {.cell layout-align=\"center\" output-location='column'}\n\n```{.r .cell-code}\nggplot(\n data = covid |> filter(signal == \"case_rate\"),\n mapping = aes(\n x = time_value,\n y = value,\n colour = geo_value\n )\n) +\n geom_point() + \n geom_smooth(se = FALSE, method = \"lm\") \n```\n\n::: {.cell-output-display}\n![](00-r-review_files/figure-revealjs/adding-geoms3-1.svg){fig-align='center'}\n:::\n:::\n\n\n::: {.notes}\n\nmapping in the `ggplot()` call is shared across the rest\n\n:::\n\n---\n\n\n\n::: {.cell layout-align=\"center\" output-location='column'}\n\n```{.r .cell-code}\nggplot(\n covid |> filter(signal == \"case_rate\"),\n aes(time_value, value, colour = geo_value)\n) +\n geom_point() + \n geom_smooth(se = FALSE, method = \"lm\") \n```\n\n::: {.cell-output-display}\n![](00-r-review_files/figure-revealjs/adding-geoms4-1.svg){fig-align='center'}\n:::\n:::\n\n\n::: {.notes}\nDon't need to name the arguments.\n\nThis is typically what ggplot code looks like.\n\nLet's go a bit further to spruce this up.\n\n:::\n\n---\n\n\n::: {.cell layout-align=\"center\" output-location='column'}\n\n```{.r .cell-code}\nggplot(\n covid, \n aes(time_value, value, colour = geo_value)\n) +\n geom_point() + \n geom_smooth(se = FALSE, method = \"lm\") +\n facet_grid(signal ~ geo_value) +\n scale_colour_manual(\n name = NULL, \n values = c(blue, orange)) +\n theme(legend.position = \"bottom\")\n```\n\n::: {.cell-output-display}\n![](00-r-review_files/figure-revealjs/adding-geoms5-1.svg){fig-align='center'}\n:::\n:::\n\n\n::: {.notes}\n\n* use facet_grid to split out states / show both signals (formula)\n* change the colour scaling, remove the annoying title\n* put the legend on the bottom\n* But the y-axis scale is shared, measurements are on different scales\n\n:::\n\n---\n\n\n\n::: {.cell layout-align=\"center\" output-location='column'}\n\n```{.r .cell-code}\nggplot(\n covid, \n aes(time_value, value, colour = geo_value)\n) +\n geom_point() + \n geom_smooth(se = FALSE, method = \"lm\") +\n facet_grid(signal ~ geo_value, scales = \"free_y\") +\n scale_colour_manual(\n name = NULL, \n values = c(blue, orange)) +\n theme(legend.position = \"bottom\")\n```\n\n::: {.cell-output-display}\n![](00-r-review_files/figure-revealjs/adding-geoms6-1.svg){fig-align='center'}\n:::\n:::\n",
+ "engine": "knitr",
+ "markdown": "---\nlecture: \"00 R, Rmarkdown, code, and `{tidyverse}`: A whirlwind tour\"\nformat: revealjs\nmetadata-files: \n - _metadata.yml\n---\n\n\n\n## {{< meta lecture >}} {.large background-image=\"gfx/smooths.svg\" background-opacity=\"0.3\"}\n\n[Stat 406]{.secondary}\n\n[{{< meta author >}}]{.secondary}\n\nLast modified -- 09 September 2024\n\n\n\n\n\n\n\n$$\n\\DeclareMathOperator*{\\argmin}{argmin}\n\\DeclareMathOperator*{\\argmax}{argmax}\n\\DeclareMathOperator*{\\minimize}{minimize}\n\\DeclareMathOperator*{\\maximize}{maximize}\n\\DeclareMathOperator*{\\find}{find}\n\\DeclareMathOperator{\\st}{subject\\,\\,to}\n\\newcommand{\\E}{E}\n\\newcommand{\\Expect}[1]{\\E\\left[ #1 \\right]}\n\\newcommand{\\Var}[1]{\\mathrm{Var}\\left[ #1 \\right]}\n\\newcommand{\\Cov}[2]{\\mathrm{Cov}\\left[#1,\\ #2\\right]}\n\\newcommand{\\given}{\\ \\vert\\ }\n\\newcommand{\\X}{\\mathbf{X}}\n\\newcommand{\\x}{\\mathbf{x}}\n\\newcommand{\\y}{\\mathbf{y}}\n\\newcommand{\\P}{\\mathcal{P}}\n\\newcommand{\\R}{\\mathbb{R}}\n\\newcommand{\\norm}[1]{\\left\\lVert #1 \\right\\rVert}\n\\newcommand{\\snorm}[1]{\\lVert #1 \\rVert}\n\\newcommand{\\tr}[1]{\\mbox{tr}(#1)}\n\\newcommand{\\brt}{\\widehat{\\beta}^R_{s}}\n\\newcommand{\\brl}{\\widehat{\\beta}^R_{\\lambda}}\n\\newcommand{\\bls}{\\widehat{\\beta}_{ols}}\n\\newcommand{\\blt}{\\widehat{\\beta}^L_{s}}\n\\newcommand{\\bll}{\\widehat{\\beta}^L_{\\lambda}}\n\\newcommand{\\U}{\\mathbf{U}}\n\\newcommand{\\D}{\\mathbf{D}}\n\\newcommand{\\V}{\\mathbf{V}}\n$$\n\n\n\n\n\n# The basics\n\n\n## Tour of Rstudio\n\nThings to note\n\n1. Console\n1. Terminal\n1. Scripts, .Rmd, Knit\n1. Files, Projects\n1. Getting help\n1. Environment, Git\n\n## Simple stuff\n\n:::: {.columns}\n::: {.column width=\"45%\"}\n\n### Vectors:\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nx <- c(1, 3, 4)\nx[1]\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 1\n```\n\n\n:::\n\n```{.r .cell-code}\nx[-1]\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 3 4\n```\n\n\n:::\n\n```{.r .cell-code}\nrev(x)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 4 3 1\n```\n\n\n:::\n\n```{.r .cell-code}\nc(x, x)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 1 3 4 1 3 4\n```\n\n\n:::\n:::\n\n\n\n:::\n\n::: {.column width=\"10%\"}\n:::\n\n::: {.column width=\"45%\"}\n\n### Matrices:\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nx <- matrix(1:25, nrow = 5, ncol = 5)\nx[1,]\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 1 6 11 16 21\n```\n\n\n:::\n\n```{.r .cell-code}\nx[,-1]\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n [,1] [,2] [,3] [,4]\n[1,] 6 11 16 21\n[2,] 7 12 17 22\n[3,] 8 13 18 23\n[4,] 9 14 19 24\n[5,] 10 15 20 25\n```\n\n\n:::\n\n```{.r .cell-code}\nx[c(1,3), 2:3]\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n [,1] [,2]\n[1,] 6 11\n[2,] 8 13\n```\n\n\n:::\n:::\n\n\n\n\n:::\n::::\n\n\n## Simple stuff\n\n::: flex\n::: w-50\n\n### Lists\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\n(l <- list(\n a = letters[1:2], \n b = 1:4, \n c = list(a = 1)))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n$a\n[1] \"a\" \"b\"\n\n$b\n[1] 1 2 3 4\n\n$c\n$c$a\n[1] 1\n```\n\n\n:::\n\n```{.r .cell-code}\nl$a\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] \"a\" \"b\"\n```\n\n\n:::\n\n```{.r .cell-code}\nl$c$a\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 1\n```\n\n\n:::\n\n```{.r .cell-code}\nl[\"b\"] # compare to l[[\"b\"]] == l$b\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n$b\n[1] 1 2 3 4\n```\n\n\n:::\n:::\n\n\n\n:::\n\n\n::: w-50\n\n### Data frames\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\n(dat <- data.frame(\n z = 1:5, \n b = 6:10, \n c = letters[1:5]))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n z b c\n1 1 6 a\n2 2 7 b\n3 3 8 c\n4 4 9 d\n5 5 10 e\n```\n\n\n:::\n\n```{.r .cell-code}\nclass(dat)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] \"data.frame\"\n```\n\n\n:::\n\n```{.r .cell-code}\ndat$b\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 6 7 8 9 10\n```\n\n\n:::\n\n```{.r .cell-code}\ndat[1,]\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n z b c\n1 1 6 a\n```\n\n\n:::\n:::\n\n\n\n\n:::\n:::\n\n[Data frames are sort-of lists and sort-of matrices]{.secondary}\n\n\n## Tibbles\n\n[These are `{tidyverse}` data frames]{.secondary}\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\n(dat2 <- tibble(z = 1:5, b = z + 5, c = letters[z]))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n# A tibble: 5 Ć 3\n z b c \n \n1 1 6 a \n2 2 7 b \n3 3 8 c \n4 4 9 d \n5 5 10 e \n```\n\n\n:::\n\n```{.r .cell-code}\nclass(dat2)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] \"tbl_df\" \"tbl\" \"data.frame\"\n```\n\n\n:::\n:::\n\n\n\n\nWe'll return to classes in a moment. A `tbl_df` is a \"subclass\" of `data.frame`.\n\nAnything that `data.frame` can do, `tbl_df` can do (better).\n\nFor instance, the printing is more informative.\n\nAlso, you can construct one by referencing previously constructed columns.\n\n\n\n# Functions\n\n\n\n## Understanding signatures\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code code-fold=\"true\"}\nsig <- sig::sig\n```\n:::\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nsig(lm)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\nfn <- function(formula, data, subset, weights, na.action, method = \"qr\", model\n = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, contrasts =\n NULL, offset, ...)\n```\n\n\n:::\n\n```{.r .cell-code}\nsig(`+`)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\nfn <- function(e1, e2)\n```\n\n\n:::\n\n```{.r .cell-code}\nsig(dplyr::filter)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\nfn <- function(.data, ..., .by = NULL, .preserve = FALSE)\n```\n\n\n:::\n\n```{.r .cell-code}\nsig(stats::filter)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\nfn <- function(x, filter, method = c(\"convolution\", \"recursive\"), sides = 2,\n circular = FALSE, init = NULL)\n```\n\n\n:::\n\n```{.r .cell-code}\nsig(rnorm)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\nfn <- function(n, mean = 0, sd = 1)\n```\n\n\n:::\n:::\n\n\n\n\n\n## These are all the same\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nset.seed(12345)\nrnorm(3)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 0.5855288 0.7094660 -0.1093033\n```\n\n\n:::\n\n```{.r .cell-code}\nset.seed(12345)\nrnorm(n = 3, mean = 0)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 0.5855288 0.7094660 -0.1093033\n```\n\n\n:::\n\n```{.r .cell-code}\nset.seed(12345)\nrnorm(3, 0, 1)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 0.5855288 0.7094660 -0.1093033\n```\n\n\n:::\n\n```{.r .cell-code}\nset.seed(12345)\nrnorm(sd = 1, n = 3, mean = 0)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 0.5855288 0.7094660 -0.1093033\n```\n\n\n:::\n:::\n\n\n\n\n* Functions can have default values.\n* You may, but don't have to, name the arguments\n* If you name them, you can pass them out of order (but you shouldn't).\n\n\n## Write lots of functions. I can't emphasize this enough.\n\n::: flex\n\n::: w-50\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nf <- function(arg1, arg2, arg3 = 12, ...) {\n stuff <- arg1 * arg3\n stuff2 <- stuff + arg2\n plot(arg1, stuff2, ...)\n return(stuff2)\n}\nx <- rnorm(100)\n```\n:::\n\n\n\n:::\n\n\n::: w-50\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\ny1 <- f(x, 3, 15, col = 4, pch = 19)\n```\n\n::: {.cell-output-display}\n![](00-r-review_files/figure-revealjs/plot-it-1.svg){fig-align='center'}\n:::\n\n```{.r .cell-code}\nstr(y1)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n num [1:100] -3.8 12.09 -24.27 12.45 -1.14 ...\n```\n\n\n:::\n:::\n\n\n\n\n:::\n:::\n\n\n## Outputs vs. Side effects\n\n::: flex\n::: w-50\n* Side effects are things a function does, outputs can be assigned to variables\n* A good example is the `hist` function\n* You have probably only seen the side effect which is to plot the histogram\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nmy_histogram <- hist(rnorm(1000))\n```\n\n::: {.cell-output-display}\n![](00-r-review_files/figure-revealjs/unnamed-chunk-9-1.svg){fig-align='center'}\n:::\n:::\n\n\n\n\n:::\n\n\n::: w-50\n\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nstr(my_histogram)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\nList of 6\n $ breaks : num [1:14] -3 -2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5 ...\n $ counts : int [1:13] 4 21 41 89 142 200 193 170 74 38 ...\n $ density : num [1:13] 0.008 0.042 0.082 0.178 0.284 0.4 0.386 0.34 0.148 0.076 ...\n $ mids : num [1:13] -2.75 -2.25 -1.75 -1.25 -0.75 -0.25 0.25 0.75 1.25 1.75 ...\n $ xname : chr \"rnorm(1000)\"\n $ equidist: logi TRUE\n - attr(*, \"class\")= chr \"histogram\"\n```\n\n\n:::\n\n```{.r .cell-code}\nclass(my_histogram)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] \"histogram\"\n```\n\n\n:::\n:::\n\n\n\n\n:::\n:::\n\n\n\n## When writing functions, program defensively, ensure behaviour\n\n::: flex\n::: w-50\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nincrementer <- function(x, inc_by = 1) {\n x + 1\n}\n \nincrementer(2)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 3\n```\n\n\n:::\n\n```{.r .cell-code}\nincrementer(1:4)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 2 3 4 5\n```\n\n\n:::\n\n```{.r .cell-code}\nincrementer(\"a\")\n```\n\n::: {.cell-output .cell-output-error}\n\n```\nError in x + 1: non-numeric argument to binary operator\n```\n\n\n:::\n:::\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nincrementer <- function(x, inc_by = 1) {\n stopifnot(is.numeric(x))\n return(x + 1)\n}\nincrementer(\"a\")\n```\n\n::: {.cell-output .cell-output-error}\n\n```\nError in incrementer(\"a\"): is.numeric(x) is not TRUE\n```\n\n\n:::\n:::\n\n\n\n\n:::\n\n\n::: w-50\n\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nincrementer <- function(x, inc_by = 1) {\n if (!is.numeric(x)) {\n stop(\"`x` must be numeric\")\n }\n x + 1\n}\nincrementer(\"a\")\n```\n\n::: {.cell-output .cell-output-error}\n\n```\nError in incrementer(\"a\"): `x` must be numeric\n```\n\n\n:::\n\n```{.r .cell-code}\nincrementer(2, -3) ## oops!\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 3\n```\n\n\n:::\n\n```{.r .cell-code}\nincrementer <- function(x, inc_by = 1) {\n if (!is.numeric(x)) {\n stop(\"`x` must be numeric\")\n }\n x + inc_by\n}\nincrementer(2, -3)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] -1\n```\n\n\n:::\n:::\n\n\n\n:::\n:::\n\n\n## How to keep track\n\n::: flex\n::: w-50\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nlibrary(testthat)\nincrementer <- function(x, inc_by = 1) {\n if (!is.numeric(x)) {\n stop(\"`x` must be numeric\")\n }\n if (!is.numeric(inc_by)) {\n stop(\"`inc_by` must be numeric\")\n }\n x + inc_by\n}\nexpect_error(incrementer(\"a\"))\nexpect_equal(incrementer(1:3), 2:4)\nexpect_equal(incrementer(2, -3), -1)\nexpect_error(incrementer(1, \"b\"))\nexpect_identical(incrementer(1:3), 2:4)\n```\n\n::: {.cell-output .cell-output-error}\n\n```\nError: incrementer(1:3) not identical to 2:4.\nObjects equal but not identical\n```\n\n\n:::\n:::\n\n\n\n:::\n\n\n::: w-50\n\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nis.integer(2:4)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] TRUE\n```\n\n\n:::\n\n```{.r .cell-code}\nis.integer(incrementer(1:3))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] FALSE\n```\n\n\n:::\n\n```{.r .cell-code}\nexpect_identical(incrementer(1:3, 1L), 2:4)\n```\n:::\n\n\n\n:::\n:::\n\n. . .\n\n::: callout-important\nIf you copy something, write a function.\n\nValidate your arguments.\n\nTo ensure proper functionality, write tests to check if inputs result in predicted outputs.\n:::\n\n\n\n# Classes and methods\n\n\n\n## Classes\n\n::: flex\n::: w-50\n\nWe saw some of these earlier:\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\ntib <- tibble(\n x1 = rnorm(100), \n x2 = rnorm(100), \n y = x1 + 2 * x2 + rnorm(100)\n)\nmdl <- lm(y ~ ., data = tib )\nclass(tib)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] \"tbl_df\" \"tbl\" \"data.frame\"\n```\n\n\n:::\n\n```{.r .cell-code}\nclass(mdl)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] \"lm\"\n```\n\n\n:::\n:::\n\n\n\n\nThe class allows for the use of \"methods\"\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nprint(mdl)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n\nCall:\nlm(formula = y ~ ., data = tib)\n\nCoefficients:\n(Intercept) x1 x2 \n -0.1742 1.0454 2.0470 \n```\n\n\n:::\n:::\n\n\n\n\n:::\n\n\n::: w-50\n\n\n* `R` \"knows what to do\" when you `print()` an object of class `\"lm\"`.\n\n* `print()` is called a \"generic\" function. \n\n* You can create \"methods\" that get dispatched.\n\n* For any generic, `R` looks for a method for the class.\n\n* If available, it calls that function.\n\n:::\n:::\n\n## Viewing the dispatch chain\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nsloop::s3_dispatch(print(incrementer))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n=> print.function\n * print.default\n```\n\n\n:::\n\n```{.r .cell-code}\nsloop::s3_dispatch(print(tib))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n print.tbl_df\n=> print.tbl\n * print.data.frame\n * print.default\n```\n\n\n:::\n\n```{.r .cell-code}\nsloop::s3_dispatch(print(mdl))\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n=> print.lm\n * print.default\n```\n\n\n:::\n:::\n\n\n\n\n\n## R-Geeky But Important\n\nThere are [lots]{.secondary} of generic functions in `R`\n\nCommon ones are `print()`, `summary()`, and `plot()`.\n\nAlso, lots of important statistical modelling concepts:\n`residuals()` `coef()` \n\n(In `python`, these work the opposite way: `obj.residuals`. The dot after the object accesses methods defined for that type of object. But the dispatch behaviour is less robust.) \n\n* The convention is\nthat the specialized function is named `method.class()`, e.g., `summary.lm()`.\n\n* If no specialized function is defined, R will try to use `method.default()`.\n\nFor this reason, `R` programmers try to avoid `.` in names of functions or objects.\n\n\n## Wherefore methods?\n\n\n* The advantage is that you don't have to learn a totally\nnew syntax to grab residuals or plot things\n\n* You just use `residuals(mdl)` whether `mdl` has class `lm`\ncould have been done two centuries ago, or a Batrachian Emphasis Machine\nwhich won't be invented for another five years. \n\n* The one draw-back is the help pages for the generic methods tend\nto be pretty vague\n\n* Compare `?summary` with `?summary.lm`. \n\n\n\n# Environments \n\n\n## Different environments\n\n* These are often tricky, but are very common.\n\n* Most programming languages have this concept in one way or another.\n\n* In `R` code run in the Console produces objects in the \"Global environment\"\n\n* You can see what you create in the \"Environment\" tab.\n\n* But there's lots of other stuff.\n\n* Many packages are automatically loaded at startup, so you have access to the functions and data inside\n\nFor example `mean()`, `lm()`, `plot()`, `iris` (technically `iris` is lazy-loaded, meaning it's not in memory until you call it, but it is available)\n\n\n\n##\n\n* Other packages require you to load them with `library(pkg)` before their functions are available.\n\n* But, you can call those functions by prefixing the package name `ggplot2::ggplot()`.\n\n* You can also access functions that the package developer didn't \"export\" for use with `:::` like `dplyr:::as_across_fn_call()`\n\n::: {.notes}\n\nThat is all about accessing \"objects in package environments\"\n\n:::\n\n\n## Other issues with environments\n\n\nAs one might expect, functions create an environment inside the function.\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nz <- 1\nfun <- function(x) {\n z <- x\n print(z)\n invisible(z)\n}\nfun(14)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 14\n```\n\n\n:::\n:::\n\n\n\n\nNon-trivial cases are `data-masking` environments.\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\ntib <- tibble(x1 = rnorm(100), x2 = rnorm(100), y = x1 + 2 * x2)\nmdl <- lm(y ~ x2, data = tib)\nx2\n```\n\n::: {.cell-output .cell-output-error}\n\n```\nError in eval(expr, envir, enclos): object 'x2' not found\n```\n\n\n:::\n:::\n\n\n\n\n* `lm()` looks \"inside\" the `tib` to find `y` and `x2`\n* The data variables are added to the `lm()` environment\n\n\n## Other issues with environments\n\n[When Knit, `.Rmd` files run in their OWN environment.]{.fourth-colour}\n\nThey are run from top to bottom, with code chunks depending on previous\n\nThis makes them reproducible.\n\nJupyter notebooks don't do this. š±\n\nObjects in your local environment are not available in the `.Rmd`\n\nObjects in the `.Rmd` are not available locally.\n\n::: {.callout-tip}\nThe most frequent error I see is:\n\n* running chunks individually, 1-by-1, and it works\n* Knitting, and it fails\n\nThe reason is almost always that the chunks refer to objects in the Environment that don't exist in the `.Rmd`\n:::\n\n##\n\n\n### This error also happens because:\n\n* `library()` calls were made globally but not in the `.Rmd` \n * so the packages aren't loaded\n\n* paths to data or other objects are not relative to the `.Rmd` in your file system \n * they must be\n\n\n* Carefully keeping Labs / Assignments in their current location will help to avoid some of these.\n\n\n# Debugging\n\n\n\n## How to fix code\n\n* If you're using a function in a package, start with `?function` to see the help\n * Make sure you're calling the function correctly.\n * Try running the examples.\n * paste the error into Google (if you share the error on Slack, I often do this first)\n * Go to the package website if it exists, and browse around\n \n* If your `.Rmd` won't Knit\n * Did you make the mistake on the last slide?\n * Did it Knit before? Then the bug is in whatever you added.\n * Did you never Knit it? Why not?\n * Call `rstudioapi::restartSession()`, then run the Chunks 1-by-1\n \n##\n \nAdding `browser()`\n\n* Only useful with your own functions.\n* Open the script with the function, and add `browser()` to the code somewhere\n* Then call your function.\n* The execution will Stop where you added `browser()` and you'll have access to the local environment to play around\n\n\n## Reproducible examples\n\n::: {.callout-tip}\n## Question I get on Slack that I hate:\n\n\"I ran the code like you had on Slide 39, but it didn't work.\"\n:::\n\n* If you want to ask me why the code doesn't work, you need to show me what's wrong.\n\n::: {.callout-warning}\n## Don't just paste a screenshot!\n\nUnless you get lucky, I won't be able to figure it out from that. And we'll both get frustrated.\n:::\n\nWhat you need is a Reproducible Example or `reprex`.\n\n* This is a small chunk of code that \n 1. runs in it's own environment \n 1. and produces the error.\n \n#\n\nThe best way to do this is with the `{reprex}` package.\n\n\n## Reproducible examples, How it works {.smaller}\n\n1. Open a new `.R` script.\n\n1. Paste your buggy code in the file (no need to save)\n\n1. Edit your code to make sure it's \"enough to produce the error\" and nothing more. (By rerunning the code a few times.)\n\n1. Copy your code.\n\n1. Call `reprex::reprex(venue = \"r\")` from the console. This will run your code in a new environment and show the result in the Viewer tab. Does it create the error you expect?\n\n1. If it creates other errors, that may be the problem. You may fix the bug on your own!\n\n1. If it doesn't have errors, then your global environment is Farblunget.\n\n1. The Output is now on your clipboard. Go to Slack and paste it in a message. Then press `Cmd+Shift+Enter` (on Mac) or `Ctrl+Shift+Enter` (Windows/Linux). Under Type, select `R`.\n\n1. Send the message, perhaps with more description and an SOS emoji.\n\n::: {.callout-note}\nBecause Reprex runs in it's own environment, it doesn't have access to any of the libraries you loaded or the stuff in your global environment. You'll have to load these things in the script.\n:::\n\n\n# Understanding `{tidyverse}`\n\n\n## `{tidyverse}` is huge\n\nCore tidyverse is nearly 30 different R packages, but we're going to just talk about a few of them.\n\nFalls roughly into a few categories:\n\n1. [Convenience functions:]{.secondary} `{magrittr}` and many many others.\n1. [Data processing:]{.secondary} `{dplyr}` and many others.\n1. [Graphing:]{.secondary} `{ggplot2}` and some others like `{scales}`.\n1. [Utilities]{.secondary}\n\n\n. . .\n\n\n\nWe're going to talk quickly about some of it, but ignore much of 2.\n\nThere's a lot that's great about these packages, especially ease of data processing.\n\nBut it doesn't always jive with base `R` (it's almost a separate proglang at this point).\n\n\n## Piping\n\nThis was introduced by `{magrittr}` as `%>%`, \n\nbut is now in base R (>=4.1.0) as `|>`.\n\nNote: there are other pipes in `{magrittr}` (e.g. `%$%` and `%T%`) but I've never used them.\n\nI've used the old version for so long, that it's hard for me to adopt the new one.\n\nThe point of the pipe is to [logically sequence nested operations]{.secondary}\n\n## Example\n\n:::: {.columns}\n::: {.column width=\"50%\"}\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nmse1 <- print(\n sum(\n residuals(\n lm(y~., data = mutate(\n tib, \n x3 = x1^2,\n x4 = log(x2 + abs(min(x2)) + 1)\n )\n )\n )^2\n )\n)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 1.991017e-29\n```\n\n\n:::\n:::\n\n\n\n\n:::\n\n\n::: {.column width=\"50%\"}\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code code-line-numbers=\"|5-6\"}\nmse2 <- tib |>\n mutate(\n x3 = x1^2, \n x4 = log(x2 + abs(min(x2)) + 1)\n ) %>% # base pipe only goes to first arg\n lm(y ~ ., data = .) |> # note the use of `.`\n residuals() |>\n magrittr::raise_to_power(2) |> # same as `^`(2)\n sum() |>\n print()\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n[1] 1.991017e-29\n```\n\n\n:::\n:::\n\n\n\n\n:::\n::::\n\n## \n\nIt may seem like we should push this all the way\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code code-line-numbers=\"|9-10\"}\ntib |>\n mutate(\n x3 = x1^2, \n x4 = log(x2 + abs(min(x2)) + 1)\n ) %>% # base pipe only goes to first arg\n lm(y ~ ., data = .) |> # note the use of `.`\n residuals() |>\n magrittr::raise_to_power(2) |> # same as `^`(2)\n sum() ->\n mse3\n```\n:::\n\n\n\n\nThis works, but it's really annoying.\n\n## A new one...\n\nJust last week, I learned\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nlibrary(magrittr)\ntib <- tibble(x = 1:5, z = 6:10)\ntib <- tib |> mutate(b = x + z)\ntib\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n# A tibble: 5 Ć 3\n x z b\n \n1 1 6 7\n2 2 7 9\n3 3 8 11\n4 4 9 13\n5 5 10 15\n```\n\n\n:::\n\n```{.r .cell-code}\n# start over\ntib <- tibble(x = 1:5, z = 6:10)\ntib %<>% mutate(b = x + z)\ntib\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n# A tibble: 5 Ć 3\n x z b\n \n1 1 6 7\n2 2 7 9\n3 3 8 11\n4 4 9 13\n5 5 10 15\n```\n\n\n:::\n:::\n\n\n\n\n\n\n## Data processing in `{dplyr}` {.smaller}\n\nThis package has all sorts of things. And it interacts with `{tibble}` generally.\n\nThe basic idea is \"tibble in, tibble out\".\n\nSatisfies [data masking]{.secondary} which means you can refer to columns by name or use helpers like `ends_with(\"_rate\")`\n\nMajorly useful operations:\n\n1. `select()` (chooses columns to keep)\n1. `mutate()` (showed this already)\n1. `group_by()`\n1. `pivot_longer()` and `pivot_wider()`\n1. `left_join()` and `full_join()`\n1. `summarise()`\n\n::: {.callout-note}\n`filter()` and `select()` are functions in Base R. \n\nSometimes you get š because it called the wrong version. \n\nTo be sure, prefix it like `dplyr::select()`.\n:::\n\n## A useful data frame\n\n\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\nlibrary(tidyverse)\ncovid <- read_csv(\"data/covid.csv\") |>\n select(geo_value, time_value, signal, value)\n\ncovid\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n# A tibble: 84 Ć 4\n geo_value time_value signal value\n \n 1 ca 2022-08-01 confirmed_7dav_incidence_prop 45.4\n 2 wa 2022-08-01 confirmed_7dav_incidence_prop 27.7\n 3 ca 2022-08-02 confirmed_7dav_incidence_prop 44.9\n 4 wa 2022-08-02 confirmed_7dav_incidence_prop 27.7\n 5 ca 2022-08-03 confirmed_7dav_incidence_prop 44.5\n 6 wa 2022-08-03 confirmed_7dav_incidence_prop 26.6\n 7 ca 2022-08-04 confirmed_7dav_incidence_prop 42.3\n 8 wa 2022-08-04 confirmed_7dav_incidence_prop 26.6\n 9 ca 2022-08-05 confirmed_7dav_incidence_prop 40.7\n10 wa 2022-08-05 confirmed_7dav_incidence_prop 34.6\n# ā¹ 74 more rows\n```\n\n\n:::\n:::\n\n\n\n\n## Examples\n\nRename the `signal` to something short.\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\ncovid <- covid |> \n mutate(signal = case_when(\n str_starts(signal, \"confirmed\") ~ \"case_rate\", \n TRUE ~ \"death_rate\"\n ))\n```\n:::\n\n\n\n\n\nSort by `time_value` then `geo_value`\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\ncovid <- covid |> arrange(time_value, geo_value)\n```\n:::\n\n\n\n\nCalculate grouped medians\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\ncovid |> \n group_by(geo_value, signal) |>\n summarise(med = median(value), .groups = \"drop\")\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n# A tibble: 4 Ć 3\n geo_value signal med\n \n1 ca case_rate 33.2 \n2 ca death_rate 0.112\n3 wa case_rate 23.2 \n4 wa death_rate 0.178\n```\n\n\n:::\n:::\n\n\n\n\n## Examples\n\nSplit the data into two tibbles by signal\n\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\ncases <- covid |> \n filter(signal == \"case_rate\") |>\n rename(case_rate = value) |> select(-signal)\ndeaths <- covid |> \n filter(signal == \"death_rate\") |>\n rename(death_rate = value) |> select(-signal)\n```\n:::\n\n\n\n\nJoin them together\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\njoined <- full_join(cases, deaths, by = c(\"geo_value\", \"time_value\"))\n```\n:::\n\n\n\n\nDo the same thing by pivoting\n\n\n\n::: {.cell layout-align=\"center\"}\n\n```{.r .cell-code}\ncovid |> pivot_wider(names_from = signal, values_from = value)\n```\n\n::: {.cell-output .cell-output-stdout}\n\n```\n# A tibble: 42 Ć 4\n geo_value time_value case_rate death_rate\n \n 1 ca 2022-08-01 45.4 0.105\n 2 wa 2022-08-01 27.7 0.169\n 3 ca 2022-08-02 44.9 0.106\n 4 wa 2022-08-02 27.7 0.169\n 5 ca 2022-08-03 44.5 0.107\n 6 wa 2022-08-03 26.6 0.173\n 7 ca 2022-08-04 42.3 0.112\n 8 wa 2022-08-04 26.6 0.173\n 9 ca 2022-08-05 40.7 0.116\n10 wa 2022-08-05 34.6 0.225\n# ā¹ 32 more rows\n```\n\n\n:::\n:::\n\n\n\n\n\n\n## Plotting with `{ggplot2}`\n\n* Everything you can do with `ggplot()`, you can do with `plot()`. But the \ndefaults are _much_ prettier.\n\n* It's also much easier to adjust by aesthetics / panels by factors.\n\n* It also uses \"data masking\": data goes into `ggplot(data = mydata)`, then the columns are available to the rest.\n\n* It (sort of) pipes, but by adding [layers]{.secondary} with `+`\n\n* It [strongly prefers]{.secondary} \"long\" data frames over \"wide\" data frames.\n\n\n\nI'll give a very fast overview of some confusing bits.\n\n# \n\nI suggest exploring\n\nš [This slide deck](https://djnavarro.net/slides-starting-ggplot/)\n\nfor more help\n\n\n\n---\n\n\n\n\n\n::: {.cell layout-align=\"center\" output-location='column'}\n\n```{.r .cell-code}\nggplot(\n data = covid |> \n filter(signal == \"case_rate\")\n) +\n geom_point(\n mapping = aes(\n x = time_value,\n y = value\n )\n ) + \n geom_smooth( \n mapping = aes( \n x = time_value, \n y = value \n ) \n ) \n```\n\n::: {.cell-output-display}\n![](00-r-review_files/figure-revealjs/adding-geoms-1.svg){fig-align='center'}\n:::\n:::\n\n\n\n\n\n\n::: {.notes}\n\n* The complete code\n* Data is specified in the ggplot, passed along\n* (we show only case_rate)\n\n\n* The Grey SE shading is pretty ugly\n* And there are two states mashed together\n* That trend is awfully wiggly\n\n:::\n\n---\n\n\n\n\n\n::: {.cell layout-align=\"center\" output-location='column'}\n\n```{.r .cell-code}\nggplot(\n data = covid |> filter(signal == \"case_rate\")\n) +\n geom_point(\n mapping = aes(\n x = time_value,\n y = value,\n colour = geo_value\n )\n ) + \n geom_smooth( \n mapping = aes( \n x = time_value, \n y = value,\n colour = geo_value\n ),\n se = FALSE,\n method = \"lm\"\n ) \n```\n\n::: {.cell-output-display}\n![](00-r-review_files/figure-revealjs/adding-geoms2-1.svg){fig-align='center'}\n:::\n:::\n\n\n\n\n::: {.notes}\n\n* Separate out the states by colour\n* straight lines instead\n* no more grey shading\n* Why do I keep writing all that mapping = stuff?\n\n:::\n\n---\n\n\n\n\n\n::: {.cell layout-align=\"center\" output-location='column'}\n\n```{.r .cell-code}\nggplot(\n data = covid |> filter(signal == \"case_rate\"),\n mapping = aes(\n x = time_value,\n y = value,\n colour = geo_value\n )\n) +\n geom_point() + \n geom_smooth(se = FALSE, method = \"lm\") \n```\n\n::: {.cell-output-display}\n![](00-r-review_files/figure-revealjs/adding-geoms3-1.svg){fig-align='center'}\n:::\n:::\n\n\n\n\n::: {.notes}\n\nmapping in the `ggplot()` call is shared across the rest\n\n:::\n\n---\n\n\n\n\n\n::: {.cell layout-align=\"center\" output-location='column'}\n\n```{.r .cell-code}\nggplot(\n covid |> filter(signal == \"case_rate\"),\n aes(time_value, value, colour = geo_value)\n) +\n geom_point() + \n geom_smooth(se = FALSE, method = \"lm\") \n```\n\n::: {.cell-output-display}\n![](00-r-review_files/figure-revealjs/adding-geoms4-1.svg){fig-align='center'}\n:::\n:::\n\n\n\n\n::: {.notes}\nDon't need to name the arguments.\n\nThis is typically what ggplot code looks like.\n\nLet's go a bit further to spruce this up.\n\n:::\n\n---\n\n\n\n\n::: {.cell layout-align=\"center\" output-location='column'}\n\n```{.r .cell-code}\nggplot(\n covid, \n aes(time_value, value, colour = geo_value)\n) +\n geom_point() + \n geom_smooth(se = FALSE, method = \"lm\") +\n facet_grid(signal ~ geo_value) +\n scale_colour_manual(\n name = NULL, \n values = c(blue, orange)) +\n theme(legend.position = \"bottom\")\n```\n\n::: {.cell-output-display}\n![](00-r-review_files/figure-revealjs/adding-geoms5-1.svg){fig-align='center'}\n:::\n:::\n\n\n\n\n::: {.notes}\n\n* use facet_grid to split out states / show both signals (formula)\n* change the colour scaling, remove the annoying title\n* put the legend on the bottom\n* But the y-axis scale is shared, measurements are on different scales\n\n:::\n\n---\n\n\n\n\n\n::: {.cell layout-align=\"center\" output-location='column'}\n\n```{.r .cell-code}\nggplot(\n covid, \n aes(time_value, value, colour = geo_value)\n) +\n geom_point() + \n geom_smooth(se = FALSE, method = \"lm\") +\n facet_grid(signal ~ geo_value, scales = \"free_y\") +\n scale_colour_manual(\n name = NULL, \n values = c(blue, orange)) +\n theme(legend.position = \"bottom\")\n```\n\n::: {.cell-output-display}\n![](00-r-review_files/figure-revealjs/adding-geoms6-1.svg){fig-align='center'}\n:::\n:::\n",
"supporting": [
"00-r-review_files"
],
diff --git a/_freeze/schedule/slides/00-r-review/figure-revealjs/adding-geoms-1.svg b/_freeze/schedule/slides/00-r-review/figure-revealjs/adding-geoms-1.svg
index 3d0fa0c..ea8f0d6 100644
--- a/_freeze/schedule/slides/00-r-review/figure-revealjs/adding-geoms-1.svg
+++ b/_freeze/schedule/slides/00-r-review/figure-revealjs/adding-geoms-1.svg
@@ -1,303 +1,306 @@
-