---
title: "| Introduction to Data Science:    \n| Presention Tools in R Markdown \n"
output:
  rmarkdown::html_document:
    highlight: espresso
    theme: lumen
  bookdown::tufte_html2:
    number_sections: no
    split_by: none
    toc: no
  prettydoc::html_pretty:
    highlight: vignette
    theme: cayman
  bookdown::html_document2:
    number_sections: no
    split_by: none
    toc: yes
    toc_float:
      collapsed: yes
---

```{r setup, include=FALSE}
library(tufte)
library(tidyverse)
library(ggplot2)
library(ggmap)
library(tint)
library(lubridate)
library(prettydoc)
library(viridis) # new color scheme
knitr::opts_chunk$set(tidy = FALSE, message = FALSE, cache.extra = packageVersion("tufte"))
options(htmltools.dir.version = FALSE)
```

# Output Formats 

R Markdown can be used to output a wide range of formats. We have already seen a bunch of these including documents (html, pdf, word, handout), html files with built-in interactive widgets, Shiny apps, and dashboards. There is a nice [gallery](http://rmarkdown.rstudio.com/gallery.html) to showcase all of these formats, as well as a [list](http://rmarkdown.rstudio.com/formats.html).

Note: The newest presentation tool available (as of 2022) is Quarto, which is a generalization of R Markdown format. It allows you to weave R, Python, Julia, and other code and output with marked up text. This is incredibly important as most organizations use a combination of computational tools. While we will still refer to R Markdown below, many of the same formats listed below are available in Quarto, which is probably the soon-to-be future standard. See [https://quarto.org/](https://quarto.org/) for more information.


## Slides {-}

There are many different ways to write slide packages in RStudio. Advantages of all of these methods are that (i) the output is an html or pdf, so it is easy to put on a website and access from anywhere, and (ii) you have already done all of your wrangling, graphics, etc. in R. So you do not need to cut and paste graphics or code clippings or anything else from RStudio into another software package like PowerPoint or Google Docs. The main disadvantage is that there is not a drag and drop way to arrange slides for these types of presentations. So if you want an image to be of a certain size at a certain location of the slide, you'll have to input those specifications, as opposed to stretching and moving with a cursor.

If you are interested in trying to write your presentation in R Markdown, my suggestion is to pick one of the formats below, download a template (I've linked to a bunch), make sure you can compile it from R Markdown, and then start editing.

### Slide presentation formats built in to R Markdown {-}

-   ioslides_presentation, an HTML presentation. Just need to include `output: ioslides_presentation` in the header of your Rmd file and then an option will appear to `Knit to HTML (ioslides)`. Here is the [documentation](http://rmarkdown.rstudio.com/ioslides_presentation_format.html), an [example](https://www.dropbox.com/s/0qk0iy3zz8o62ug/shiny-debugging.html?dl=1), and the [Rmd for the example](https://www.dropbox.com/s/8wr4o42bcrh6ays/shiny-debugging.Rmd?dl=1). These files are from one of Garret Grolemund's repositories [here](https://github.com/rstudio/ShinyDeveloperConference/tree/main/Debugging).
-   slidy_presentation, an HTML presentation. Same thing as above. Just include `output: slidy_presentation` and an option will appear to `Knit to HTML (Slidy)`. Here is the [documentation](http://rmarkdown.rstudio.com/slidy_presentation_format.html).
-   beamer_presentation, a PDF presentation with LaTeX Beamer. Same as above again. Just include `output: beamer_presentation` and then you can `Knit to PDF (Beamer)`.

### Slide presentation formats available via other packages {-}

-   revealjs::revealjs_presentation, an HTML presentation that requires the `revealjs` package. Here is the [documentation](http://rmarkdown.rstudio.com/revealjs_presentation_format.html), an [example](https://www.dropbox.com/s/v7agbem213vsds1/slides.html?dl=1), and the [Rmd for the example](https://www.dropbox.com/s/phqae91hu0j4e4v/slides.Rmd?dl=1). These files are from one of Garret Grolemund's repositories [here](https://github.com/rstudio/ShinyDeveloperConference/tree/master/Reactivity).
-   rmdshower, an HTML presentation that requires the `rmdshower` package. [Here](http://mangothecat.github.io/rmdshower/skeleton.html#shower-presentations-with-r-markdown) is an example and the code to generate it can be found in this [repository](https://github.com/MangoTheCat/rmdshower).
-   [Slidify](https://slidify.github.io/) is a wrapper package that enables you to use many different types of presentations. Here is a [review](https://benjaminlmoore.wordpress.com/2014/02/24/slidify-presentations-in-r-markdown/) and a pretty good [tutorial](http://www.jvcasillas.com/slidify_tutorial/#1), the code for which you can find [here](https://github.com/jvcasill/slidify_tutorial/tree/gh-pages).

## Reports / Websites {-}

You have all used the standard `output:html_document` to knit your Rmd file into an html file. For your technical blog posts, you can stick to that, or try tweaking some options. Here are some examples:

-   You can change the appearance and style of the output of the html_document by changing the `theme` and `highlight` options. I've changed these in one knitting option above with the `lumen` theme and `espresso` highlight. You can find the full list of options [here](http://rmarkdown.rstudio.com/html_document_format.html#appearance_and_style).
-   You can load the `prettydoc` package, and use one of its themes. You can find the full list in the [documentation](https://github.com/yixuan/prettydoc/) or this [tutorial](https://yixuan.cos.name/prettydoc/tactile.html).
-   Some [alternative Markdown templates](https://github.com/hrbrmstr/markdowntemplates)
-   The `bookdown` package was designed to write books in R Markdown, but you can also use it write single html files or pdf handouts. I've been using it all semester in conjunction with the `tufte_html2` option, which leaves a wide margin for notes and side figures. Here is the [documentation](https://bookdown.org/yihui/bookdown/), [a tutorial video](https://www.rstudio.com/resources/webinars/introducing-bookdown/), and a bunch of [books that were written with the package](https://bookdown.org/). Check out the [list of contributors](https://cran.rstudio.com/web/packages/bookdown/index.html).

Here a couple others you probably will not need for this project:

-   The [blogdown package](https://github.com/rstudio/blogdown) helps you set up an actual blogs with multiple posts. Here is a [tutorial](https://bookdown.org/yihui/blogdown/) (written in `bookdown` ofcourse) and an [example blog](https://rviews.rstudio.com/).

-   The [rticles package](https://github.com/rstudio/rticles) helps you use R Markdown to write an article that conforms to a specific journal's template.

### Test {-}

Below is some sample content to test out some of these output options. I've set everything up in the header of this Rmd file. All you have to do is knit it with different options and check out the output html file.

#### A sample footnote[^1] {-}

[^1]: This is a footnote.

#### How a code chunk is displayed: {-}

```{r}
data_site <-
  "https://bcheggeseth.github.io/112_fall_2022/data/2014-Q4-Trips-History-Data.rds"
Trips <- readRDS(gzcon(url(data_site)))
Stations <- read_csv("https://bcheggeseth.github.io/112_fall_2022/data/DC-Stations.csv")
```

#### Graphic from ggplot: {-}

```{r,echo=FALSE}

busyBikes <- Trips %>%
  group_by(bikeno) %>%
  summarise(count = n()) %>%
  arrange(desc(count)) %>%
  head(3)
singleBike <- Trips %>%
  filter(bikeno == busyBikes$bikeno[1]) %>%
  arrange(sdate) %>%
  select(sdate, sstation, edate, estation)

singleTidy <- bind_rows(
  singleBike %>%
    select(date = sdate, station = sstation) %>%
    mutate(key = "start"),
  singleBike %>%
    select(date = edate, station = estation) %>%
    mutate(key = "end")
) %>%
  arrange(date) %>%
  left_join(Stations, by = c("station" = "name"))
```

```{r,echo=FALSE, cache=TRUE}
stops <- singleTidy %>%
  select(station, lat, long, date) %>%
  head(102) %>%
  mutate(elapsed_hours = as.numeric(difftime(date, date[1], units = "hours"))) %>%
  mutate(order = 1:102)

myMap <- get_stamenmap(c(-77.1, 38.87, -76.975, 38.95), zoom = 14, maptype = "terrain") # centered at Logan Circle

ggmap(myMap) +
  geom_path(data = stops, aes(x = long, y = lat, color = elapsed_hours), size = 1.3) +
  scale_color_distiller(palette = "Greys") +
  labs(color = "Elapsed Hours")
```

#### Interactive map with the leaflet package: {-}

```{r,echo=FALSE}
library(leaflet)
pal <- colorNumeric(
  palette = "Greys",
  domain = stops$order, reverse = TRUE
)
leaflet(stops) %>%
  setView(-77.0296, 38.9096, zoom = 13) %>% # Logan Circle coords
  addProviderTiles("OpenStreetMap.Mapnik") %>% # this fixes a bug in addTiles() %>%
  addCircleMarkers(
    lat = ~lat, lng = ~long, color = ~ pal(order),
    popup = ~ paste(as.character(order), ": ", station, sep = "")
  ) %>%
  addPolylines(lat = ~lat, lng = ~long)
```

#### Number of daily net departures for four different stations: {-}

```{r,echo=FALSE}
num_daily_departures <- Trips %>%
  mutate(month = lubridate::month(sdate)) %>%
  mutate(day = lubridate::day(sdate)) %>%
  group_by(month, day, sstation) %>%
  summarise(num_departures = n())
num_daily_arrivals <- Trips %>%
  mutate(month = lubridate::month(edate)) %>%
  mutate(day = lubridate::day(edate)) %>%
  group_by(month, day, estation) %>%
  filter(month > 9) %>%
  summarise(num_arrivals = n())
NetTraffic <- num_daily_departures %>%
  full_join(num_daily_arrivals, by = c("sstation" = "estation", "month" = "month", "day" = "day"))
NetTraffic[is.na(NetTraffic)] <- 0
NetTraffic <- NetTraffic %>%
  mutate(total_events = num_departures + num_arrivals) %>%
  mutate(net_departures = num_departures - num_arrivals) %>%
  rename(station = sstation) %>%
  group_by(station) %>%
  mutate(tot = sum(total_events)) %>%
  filter(tot > 6000) %>%
  ungroup() %>%
  mutate(date = ymd(paste("2014", as.character(month), as.character(day), sep = ""))) %>%
  mutate(wday = wday(date, label = TRUE))
```

```{r echo=FALSE,fig.fullwidth=TRUE}
knitr::kable(NetTraffic[1:10, c(9, 10, 3:7)], caption = "First ten rows of the NetTraffic table.")
```

```{r,echo=FALSE}
NetTrafficSelect <- NetTraffic %>%
  filter(station %in% c("Massachusetts Ave & Dupont Circle NW", "16th & Harvard St NW", "Lincoln Memorial", "Columbus Circle / Union Station")) %>%
  select(date, station, net_departures)
```

```{r,echo=FALSE}
library(xts)
NetTrafficSelectWide <- NetTrafficSelect %>%
  spread(key = station, value = net_departures)
NetTrafficSelectXTS <- xts(NetTrafficSelectWide[, 2:5], order.by = NetTrafficSelectWide$date)
```

#### Visualization with dygraphs: {-}

```{r, echo=FALSE,fig.width=12}
library(dygraphs)
dygraph(NetTrafficSelectXTS, main = "Daily Net Departures at Four Select Stations") %>%
  dyRangeSelector() %>%
  dyOptions(
    drawPoints = TRUE,
    pointSize = 5,
    strokeWidth = 3,
    colors = RColorBrewer::brewer.pal(4, "Set2")
  ) %>%
  dyLegend(width = 1000)
```

#### Alternative visualization with plotly: {-}

```{r,echo=FALSE,fig.fullwidth=TRUE,fig.width=12}
library(plotly)
p <- ggplot(
  NetTrafficSelect,
  aes(x = date, y = net_departures, fill = station)
) +
  geom_col(position = "dodge")
ggplotly(p)
```
