Lecture Notes: Choose Your Adventure

Version 1.0.0

Learning Objectives

By the end of this class, we will cover as much of the following as we can:

  • More R Basics:
    • vectors and lists
    • Make a reproducible example using the reprex package.
    • Use of {}.
    • attributes
    • style guides
  • Turning your GitHub repository into a Website
  • Turning your Rmd into a presentation (2 min)

Parallel Resources

This topic parallels the following resources. Take about 30 minutes to get acquainted with the following before coming to class:

We suggest referring to this material when engaging with today’s topic.

Additional Resources

Quiz

No quiz today

Demonstration

library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ ggplot2 3.3.2     ✓ purrr   0.3.4
## ✓ tibble  3.0.3     ✓ dplyr   1.0.2
## ✓ tidyr   1.1.2     ✓ stringr 1.4.0
## ✓ readr   1.3.1     ✓ forcats 0.5.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(gapminder)
library(palmerpenguins)
knitr::opts_chunk$set(error = TRUE)

Start with reprex:

reprex::reprex(mean(rnorm(10)))
## Rendering reprex...
mean(rnorm(10))
#> [1] -0.343914

Created on 2020-10-22 by the reprex package (v0.3.0)

Part I: R Basics beyond the worksheet

Curly brackets

Curly brackets can hold multiple lines of code, and outputs the result at the end.

There’s not a whole lot of difference if you just using them on their own:

y <- {
  x <- 10
  x ^ 2
  x ^ 3
}
y
## [1] 1000

They start to matter when you need to add multiple lines of code as an argument.

Question 1

You’ve encountered an error in the following code, and want to ask for help. Write a reprex to send over to someone, and paste it below the code chunk.

library(tidyverse)
library(gapminder)
gapminder %>% 
   group_by(Country) %>% 
   summarise(mean_pop == mean(pop))
reprex::reprex({
  library(tidyverse)
  library(gapminder)
  gapminder %>% 
    group_by(Country) %>% 
    summarise(mean_pop == mean(pop))
})
## Rendering reprex...
library(tidyverse)
library(gapminder)
gapminder %>% 
  group_by(Country) %>% 
  summarise(mean_pop == mean(pop))
#> Error: Must group by variables found in `.data`.
#> * Column `Country` is not found.

Created on 2020-10-22 by the reprex package (v0.3.0)

Question 2

Sample 10 rows randomly from the gapminder tibble using dplyr::sample_n(), so that you get the same results each time. Do this all in a single pipe.

gapminder %>% 
  {
    my_lm <- lm(lifeExp ~ gdpPercap, data = .)
    beta1 <- coef(my_lm)[2]
    .
  } %>% 
  sample_n(10)
## # A tibble: 10 x 6
##    country     continent  year lifeExp      pop gdpPercap
##    <fct>       <fct>     <int>   <dbl>    <int>     <dbl>
##  1 Madagascar  Africa     1997    55.0 14165114      986.
##  2 Morocco     Africa     1992    65.4 25798239     2948.
##  3 Mauritius   Africa     1977    64.9   913025     3711.
##  4 Chile       Americas   1972    63.4  9717524     5494.
##  5 Zambia      Africa     1957    44.1  3016000     1312.
##  6 Nicaragua   Americas   1977    57.5  2554598     5486.
##  7 Ethiopia    Africa     1952    34.1 20860941      362.
##  8 Iceland     Europe     1952    72.5   147962     7268.
##  9 Congo, Rep. Africa     1962    48.4  1047924     2465.
## 10 Australia   Oceania    1982    74.7 15184200    19477.

Attributes

Did you know that a tibble is actually just a list?

is.list(penguins)
## [1] TRUE

Why, then, doesn’t it look like a list? Because it carries metadata that tells R to treat it in a special way. The metadata is held in something called attributes.

The attributes of penguins:

attributes(penguins)
## $names
## [1] "species"           "island"            "bill_length_mm"   
## [4] "bill_depth_mm"     "flipper_length_mm" "body_mass_g"      
## [7] "sex"               "year"             
## 
## $row.names
##   [1]   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18
##  [19]  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36
##  [37]  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54
##  [55]  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72
##  [73]  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90
##  [91]  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108
## [109] 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
## [127] 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
## [145] 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
## [163] 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
## [181] 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
## [199] 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
## [217] 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
## [235] 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
## [253] 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
## [271] 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
## [289] 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
## [307] 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
## [325] 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
## [343] 343 344
## 
## $class
## [1] "tbl_df"     "tbl"        "data.frame"
penguins[1, 3]
## # A tibble: 1 x 1
##   bill_length_mm
##            <dbl>
## 1           39.1

Remove attributes with unclass():

#unclass(penguins)

Question 3

Make the following list stored in homemade_tibble a tibble by changing the attributes.

(homemade_tibble <- list(
  species = c("Chinstrap", "Adelie"),
  body_mass_g = c(3405, 2304)
))
## $species
## [1] "Chinstrap" "Adelie"   
## 
## $body_mass_g
## [1] 3405 2304
attributes(homemade_tibble)
## $names
## [1] "species"     "body_mass_g"
attr(homemade_tibble, which = "class") <- c("tbl_df" ,    "tbl"   ,     "data.frame")
attr(homemade_tibble, which = "row.names") <- 1:2
homemade_tibble
## # A tibble: 2 x 2
##   species   body_mass_g
## * <chr>           <dbl>
## 1 Chinstrap        3405
## 2 Adelie           2304

Question 4

Here’s a regression model:

(my_model <- lm(mpg ~ wt, data = mtcars))
## 
## Call:
## lm(formula = mpg ~ wt, data = mtcars)
## 
## Coefficients:
## (Intercept)           wt  
##      37.285       -5.344

What object is this? Use unclass() to find out. What are its attributes?

unclass(my_model)
## $coefficients
## (Intercept)          wt 
##   37.285126   -5.344472 
## 
## $residuals
##           Mazda RX4       Mazda RX4 Wag          Datsun 710      Hornet 4 Drive 
##          -2.2826106          -0.9197704          -2.0859521           1.2973499 
##   Hornet Sportabout             Valiant          Duster 360           Merc 240D 
##          -0.2001440          -0.6932545          -3.9053627           4.1637381 
##            Merc 230            Merc 280           Merc 280C          Merc 450SE 
##           2.3499593           0.2998560          -1.1001440           0.8668731 
##          Merc 450SL         Merc 450SLC  Cadillac Fleetwood Lincoln Continental 
##          -0.0502472          -1.8830236           1.1733496           2.1032876 
##   Chrysler Imperial            Fiat 128         Honda Civic      Toyota Corolla 
##           5.9810744           6.8727113           1.7461954           6.4219792 
##       Toyota Corona    Dodge Challenger         AMC Javelin          Camaro Z28 
##          -2.6110037          -2.9725862          -3.7268663          -3.4623553 
##    Pontiac Firebird           Fiat X1-9       Porsche 914-2        Lotus Europa 
##           2.4643670           0.3564263           0.1520430           1.2010593 
##      Ford Pantera L        Ferrari Dino       Maserati Bora          Volvo 142E 
##          -4.5431513          -2.7809399          -3.2053627          -1.0274952 
## 
## $effects
##  (Intercept)           wt                                                     
## -113.6497374  -29.1157217   -1.6613339    1.6313943    0.1111305   -0.3840041 
##                                                                               
##   -3.6072442    4.5003125    2.6905817    0.6111305   -0.7888695    1.1143917 
##                                                                               
##    0.2316793   -1.6061571    1.3014525    2.2137818    6.0995633    7.3094734 
##                                                                               
##    2.2421594    6.8956792   -2.2010595   -2.6694078   -3.4150859   -3.1915608 
##                                                                               
##    2.7346556    0.8200064    0.5948771    1.7073457   -4.2045529   -2.4018616 
##                           
##   -2.9072442   -0.6494289 
## 
## $rank
## [1] 2
## 
## $fitted.values
##           Mazda RX4       Mazda RX4 Wag          Datsun 710      Hornet 4 Drive 
##           23.282611           21.919770           24.885952           20.102650 
##   Hornet Sportabout             Valiant          Duster 360           Merc 240D 
##           18.900144           18.793255           18.205363           20.236262 
##            Merc 230            Merc 280           Merc 280C          Merc 450SE 
##           20.450041           18.900144           18.900144           15.533127 
##          Merc 450SL         Merc 450SLC  Cadillac Fleetwood Lincoln Continental 
##           17.350247           17.083024            9.226650            8.296712 
##   Chrysler Imperial            Fiat 128         Honda Civic      Toyota Corolla 
##            8.718926           25.527289           28.653805           27.478021 
##       Toyota Corona    Dodge Challenger         AMC Javelin          Camaro Z28 
##           24.111004           18.472586           18.926866           16.762355 
##    Pontiac Firebird           Fiat X1-9       Porsche 914-2        Lotus Europa 
##           16.735633           26.943574           25.847957           29.198941 
##      Ford Pantera L        Ferrari Dino       Maserati Bora          Volvo 142E 
##           20.343151           22.480940           18.205363           22.427495 
## 
## $assign
## [1] 0 1
## 
## $qr
## $qr
##                     (Intercept)            wt
## Mazda RX4            -5.6568542 -18.199514334
## Mazda RX4 Wag         0.1767767   5.447820482
## Datsun 710            0.1767767   0.148230003
## Hornet 4 Drive        0.1767767  -0.016055881
## Hornet Sportabout     0.1767767  -0.057356801
## Valiant               0.1767767  -0.061027994
## Duster 360            0.1767767  -0.081219555
## Merc 240D             0.1767767  -0.011466889
## Merc 230              0.1767767  -0.004124504
## Merc 280              0.1767767  -0.057356801
## Merc 280C             0.1767767  -0.057356801
## Merc 450SE            0.1767767  -0.172999378
## Merc 450SL            0.1767767  -0.110589098
## Merc 450SLC           0.1767767  -0.119767081
## Cadillac Fleetwood    0.1767767  -0.389599760
## Lincoln Continental   0.1767767  -0.421539139
## Chrysler Imperial     0.1767767  -0.407037927
## Fiat 128              0.1767767   0.170257160
## Honda Civic           0.1767767   0.277639553
## Toyota Corolla        0.1767767   0.237256431
## Toyota Corona         0.1767767   0.121613854
## Dodge Challenger      0.1767767  -0.072041573
## AMC Javelin           0.1767767  -0.056439003
## Camaro Z28            0.1767767  -0.130780659
## Pontiac Firebird      0.1767767  -0.131698458
## Fiat X1-9             0.1767767   0.218900467
## Porsche 914-2         0.1767767   0.181270739
## Lotus Europa          0.1767767   0.296362637
## Ford Pantera L        0.1767767  -0.007795696
## Ferrari Dino          0.1767767   0.065628162
## Maserati Bora         0.1767767  -0.081219555
## Volvo 142E            0.1767767   0.063792566
## attr(,"assign")
## [1] 0 1
## 
## $qraux
## [1] 1.176777 1.046354
## 
## $pivot
## [1] 1 2
## 
## $tol
## [1] 1e-07
## 
## $rank
## [1] 2
## 
## attr(,"class")
## [1] "qr"
## 
## $df.residual
## [1] 30
## 
## $xlevels
## named list()
## 
## $call
## lm(formula = mpg ~ wt, data = mtcars)
## 
## $terms
## mpg ~ wt
## attr(,"variables")
## list(mpg, wt)
## attr(,"factors")
##     wt
## mpg  0
## wt   1
## attr(,"term.labels")
## [1] "wt"
## attr(,"order")
## [1] 1
## attr(,"intercept")
## [1] 1
## attr(,"response")
## [1] 1
## attr(,".Environment")
## <environment: R_GlobalEnv>
## attr(,"predvars")
## list(mpg, wt)
## attr(,"dataClasses")
##       mpg        wt 
## "numeric" "numeric" 
## 
## $model
##                      mpg    wt
## Mazda RX4           21.0 2.620
## Mazda RX4 Wag       21.0 2.875
## Datsun 710          22.8 2.320
## Hornet 4 Drive      21.4 3.215
## Hornet Sportabout   18.7 3.440
## Valiant             18.1 3.460
## Duster 360          14.3 3.570
## Merc 240D           24.4 3.190
## Merc 230            22.8 3.150
## Merc 280            19.2 3.440
## Merc 280C           17.8 3.440
## Merc 450SE          16.4 4.070
## Merc 450SL          17.3 3.730
## Merc 450SLC         15.2 3.780
## Cadillac Fleetwood  10.4 5.250
## Lincoln Continental 10.4 5.424
## Chrysler Imperial   14.7 5.345
## Fiat 128            32.4 2.200
## Honda Civic         30.4 1.615
## Toyota Corolla      33.9 1.835
## Toyota Corona       21.5 2.465
## Dodge Challenger    15.5 3.520
## AMC Javelin         15.2 3.435
## Camaro Z28          13.3 3.840
## Pontiac Firebird    19.2 3.845
## Fiat X1-9           27.3 1.935
## Porsche 914-2       26.0 2.140
## Lotus Europa        30.4 1.513
## Ford Pantera L      15.8 3.170
## Ferrari Dino        19.7 2.770
## Maserati Bora       15.0 3.570
## Volvo 142E          21.4 2.780
attributes(my_model)
## $names
##  [1] "coefficients"  "residuals"     "effects"       "rank"         
##  [5] "fitted.values" "assign"        "qr"            "df.residual"  
##  [9] "xlevels"       "call"          "terms"         "model"        
## 
## $class
## [1] "lm"

Style Guide

Write code that’s easier to read by referring to the tidyverse style guide

Part 2: Turning Your GitHub Repo into a Website

It’s common to turn your GitHub repository into a website. Case in point: stat545.stat.ubc.ca; vincenzocoia.com. At the very least, this is useful for making your html files visible as a webpage.

GitHub Pages

Activate GitHub pages in your repo’s settings, and your repository’s files will be served on a website.

By default, your main README is shown on the website homepage. So, if you put links to other files in your README, you now have a navigable (albeit rudimentary) website.

If you want a beautiful website, you have a couple options:

  1. Code up your own css files etc. (Hard)
  2. Use a template (easier)
  3. GitHub Pages is powered by Jekyll behind the scenes. Dean Attali made a template called Beautiful Jekyll. I used this for some time.
  4. Use blogdown (see the section after next). stat545.stat.ubc.ca and vincenzocoia.com both use this.

Viewing an HTML file from your GitHub repo

Viewing an HTML file on GitHub only shows you the HTML code, not the rendered script. You’ll need to provide a link to a rendered, viewable version of each HTML file you produce. Here’s how you do that using GitHub Pages:

  1. Enable “GitHub pages” on your repo:
    • Go to “settings” on your repo, and stay on the default “Options” tab.
    • Scroll down to the “GitHub Pages” section.
    • Under “Source”, click the “None” drop-down button, and select the branch you want to turn into a website (probably “Master”).
  2. Also under the “GitHub Pages” section, you’ll find your website URL. Make note of this URL.
    • This URL will show a rendered version of your repo’s README, but this is not important.

Just by enabling GitHub Pages, your HTML files are now viewable rendered by your browser. Technically, you just turned your GitHub repo into a website. The only trick is navigating to that HTML page, since there’s no default interface to your website.

  1. Obtain the URL to HTML file on your repo:
    • Start with your GitHub Pages URL that you made note of in Step 2. This points to the root of your repository.
    • Get the path to an HTML file you want to view. It should be something like /path/to/file.html (in this case, file.html lives in the to folder, which lives in the path folder in the root of your repo).
    • Append the path to the HTML file to your GitHub Pages URL. Try the URL to see that it works.
  2. Make it easy for a visitor to your repo to find the rendered HTML file! Add a link to the rendered HTML file somewhere in your repo, probably in a README file in your homework folder.

Blogdown

Blogdown (an R package) is actually just a wrapper around a non-R software called hugo.

Let’s explore:

  1. Check out the blogdown website. This is really the only step you need.
  2. Check out the recommended workflow
  3. Add this updated html page to the STAT 545 website?

Part 3: Making Presentation Slides from Rmd

  1. Try knitting this to ioslides_presentation.
  2. Take a look at other options beside ioslides.
  • Feeling fancy? Try output: revealjs::revealjs_presentation.