```{r, include=FALSE}
###########################
# STYLE EDITS: IGNORE THIS
###########################

# normally you'll want to include this with the libraries at the beginning of your document
knitr::opts_chunk$set(message = FALSE) # include this if you don't want markdown to knit messages
knitr::opts_chunk$set(warning = FALSE) # include this if you don't want markdown to knit warnings
knitr::opts_chunk$set(echo = FALSE) # set echo = FALSE to hide code from html output
```

# Introduction

This document demonstrates the following:

2. [A discussion for smart coding in an `.Rmd` file](#sec-leverage)
3. [Table and Figure Captions & Formatting](#figures-and-tables-captions-and-formating)
4. [Cross-Referencing](#cross-referencing)
5. [Footnotes](#footnotes)
6. [Citations](#citations-and-document-references)
7. [Code Appendix](#code-appendix)

This document mainly highlights things descripted in [`bookdown`](https://bookdown.org/yihui/bookdown/)'s documentation online. Additionally, more details about everything mentioned in this document can be found in a (poorly written) [blog](https://benjaminleroy.github.io/pages/blog/public/post/2020/09/14/professional-rmd/) I wrote up.


# Leveraging Rmd to the fullest {#sec-leverage}

You can find a lot of examples of the functionality of Rmarkdown on this [cheat sheet](https://rstudio.com/wp-content/uploads/2015/02/rmarkdown-cheatsheet.pdf) from Rstudio.

We will highlight a few basic things here:

## Putting values from `R` code blocks inline

Suppose you do some analysis that ends with your final value `my_var` wanting to be reported (e.g. the proportion of successful predictions, etc). The following example ([Example 1](#example-1)) demostrates included the value of `my_var` inline using `` `r "\u0060r my_var\u0060"` ``^[Technically, we use `sprintf("%1.4f", my_var)` but still.]

### Example 1 
  
```{r echo = T}

# basic input output demo
my_var <- pi
```

My variable (`my_var`) is actually $\pi$ which round to the 4th digit here: `r sprintf("%1.4f", my_var)`.


## Hide warnings and messages from loading packages 

Either in the initial code block (where we do it for all future code blocks), or in headers of code blocks with 

````markdown
`r ''````{r message = F, warning = F}
library(tidyverse)
```
````

## Don't accidentally print out massive data frame
Try things  like `head(df)` instead

## Be reproducible

Use `set.seed(100)` to make sure any randomness is constaint in it's randomness.


# Figures and tables captions and formating

Some guidelines:

1. always provide useful captions for tables and figures (see below)
2. always label your figures and provide useful titles

Tables:
You'll find that packages `knitr` (and `knitrExtra`) or `xtable` are useful to help make presentable tables. Moreover `broom` can help compress lots of models in `R` into data frames that can then be passed into these functions (ex. `broom::tidy`).

An example of a table with a caption (using `knitr::kable`) can be seen in Table \@ref(tab:table-example). In this example, other formatting comes from the `kableExtra::kable_styling` function, where we use `latex_options = "HOLD_position"` to encourage the stay as close as possible to where it was run in the `Rmd` file.

```{r table-example}
# table demo

library(pander)
library(tidyverse)
library(reshape2)
library(kableExtra)
library(knitr)

# titantic table

titantic <- read_csv(paste0("https://raw.githubusercontent.com/",
                            "benjaminleroy/stat315summer_data/",
                            "master/assignments/assignment03/titanic.csv"))
titantic %>% group_by(Pclass, Sex) %>%
  summarize(t = n()) %>% dcast(Pclass ~ Sex) %>%
  rename(`Passenger Class` = Pclass) %>%
  kable(format = "latex",
        caption = paste("Passengers Gender and Class divisions on the Titanic.",
                        "More 'lower class' passangers where males seeking a",
                        "better life. See Figure \\ref{fig:fig-example}."),
        booktabs = T) %>%
  kable_styling(latex_options = "HOLD_position")
```

Figure captions go at the top of the figure code block (in the `fig.cap` parameter), as can be seen in Figure \@ref(fig:fig-example). Most Figure parameters occur in the code block's discription, for example: `fig.align` to determine alignment of the figure, and we can change the size of the figure with `fig.width` and `fig.height` (and `fig.asp`). The parameter `fig.pos` allows us to define floating in a similar way as the table options.

```{r fig-example, fig.cap = "Survival rates across differ passenger rates. This figure doesn't tell the full story as table \\ref{tab:table-example} shows that more of the lower class passengers were male.", fig.align="center",fig.pos="H",fig.width=4, fig.asp=.75}

# titantic visual

titantic %>% ggplot() +
  geom_bar(aes(fill = factor(Survived, 
                             levels = c(0,1), 
                             labels = c("No", "Yes")), Pclass), 
           position = "fill") +
  scale_fill_manual(values = c("black", "lightblue")) +
  labs(fill = "Survived",
       y = "Proportion",
       x = "Passenger Class",
       title = "Survival Rates for Passenger Classes")
```

## Inserting premade images

Professor Junker also provided you with the following links to embed figures (these both work in code chunks but do not work with images from the internet):

- https://stackoverflow.com/questions/46901438/bringing-an-image-into-rmarkdown. 

- http://zevross.com/blog/2017/06/19/tips-and-tricks-for-working-with-images-and-figures-in-r-markdown-documents/ 

````markdown
`r ''````{r scotty, fig.cap = "Go Tartans!", echo = T, fig.align="center", 
fig.pos="H", fig.height=1,fig.asp=2}
knitr::include_graphics("images/scotty.png")
```
````

```{r scotty, fig.cap = "Go Tartans!", echo = F, fig.align="center", fig.pos="H", fig.height=1,fig.asp=2}
knitr::include_graphics("images/scotty.png")
```

Outside of a code chunk you can also use the format:

`![](local/path/to/file)`

## Including images from the web

Below, in figure \@ref(fig:fig-webimage) we show an example of including an image from the web.

```{r fig-webimage, fig.cap = "Random image from the web. Not at all related to Figure \\ref{fig:fig-example}.", echo=F, message=F, warning=F, fig.align="center", out.width = "100%"}

# example of how to include images from the web (instead of local files)

# annoying code to create the figure (for pdf and html)
# for just html could do:
# ![](https://raw.githubusercontent.com/benjaminleroy/36-350-summer-data/master/Week5/percolation1.png)
url <- "https://raw.githubusercontent.com/benjaminleroy/36-350-summer-data/master/Week5/percolation1.png"
library(png)
library(RCurl)
url_cont <- getURLContent(url)
img <- readPNG(url_cont)
rimg <- as.raster(img) # raster multilayer object
r <- nrow(rimg) / ncol(rimg) # image ratio
plot(rimg)
```

# Cross-Referencing

Throughout the above document we have multiple cross-references to different things. In `bookdown::pdf_document2` we reference the item with the code `\@ref(item-name)`. Be aware that `bookdown` doesn't allow for reference names like `item_name` but does allow for `item-name`.

## Tables

For tables, like Table \@ref(tab:table-example), we will commonly be referring to a code block - so we use the code blocks' label (the first name in the code block: `{r table-example}`). If we'd made our own table in markdown (as demonstrated below in and in the Rmarkdown cheatsheet referenced in Section \@ref(sec-leverage))

````markdown
Table: (\#tab:markdown-table) Model Scores

Model | Score
------|-------
1     | 1
2     | .5
3     | 2
4     |.75
5     | 4
````

Table: (\#tab:markdown-table) Model Scores

Model | Score
------|-------
1     | 1
2     | .5
3     | 2
4     |.75
5     | 4

We can reference it using `\@ref{tab:markdown-table}` (Table \@ref(tab:markdown-table)). In this situation - you must give it the "tab" start.

Note that tables get the `tab:label` structure.

## Figures

For tables, like Figure \@ref(fig:fig-example), we will commonly be referring to a code block - so we use the code blocks' label (the first name in the code block: `{r fig-example}`). We can use similar referencing to images pull in from online or a file (but should also use a code block - as demonstrated above.

Note that figures get the `fig:label` structure.

## Sections

Sections are a little difference. To reference a section pandoc creations a linking to the name with no spaces or capitilization - transforming "I'm demonstrating. Thanks" to "im-demonstrating-thanks". Additionally if we put `{#label}` at the end of the section title (like I did in Section \@ref(sec-leverage)) you can then reference the section with just `\@ref{label}`.

Note that sections don't get the `sec:label` but just get a straight `label` structure.

## Equations 

The below equation (named equation \@ref(eq:pythag)) is able to be referenced as we have inserted a label at the end of the equation as well. Note that equations get the `eq:label` structure.

\begin{equation}
a^2 + b^2 = c^2
(\#eq:pythag)
\end{equation}

## Final notes

As Pandocs converts the document to latex, sometimes you can just use the standard latex notation: `\ref{tab:label}`. This is done in the captions of Table \@ref(tab:table-example) and Figure \@ref(fig:fig-example).


# Footnotes

I enjoy putting in footnotes, and the can be very useful. There is a footnote in Section \@ref(putting-values-from-r-code-blocks-inline), and it's pretty simple, just do `^[footnote-text]` and the footnote will appear at the location and with footnote text at the bottom of the page^[Footnotes are cool!].

# Citations and Document References

There's a lot of ways to reference documents (see my messy [blog](https://benjaminleroy.github.io/pages/blog/public/post/2020/09/14/professional-rmd/) for some guidance), but in this document we have done so in the following way

## Where are the references

We've storied a set of references in the file called `mybib.bib`. We are using the `.bib` format, more details on this format can be found on [wikipedia](https://en.wikipedia.org/wiki/BibTeX#/Bibliographic_information_file).

## How we tell the .Rmd where to look

At the top of this document, we have a `yaml` part that looks like the following

```
---
blah
---
```

The first thing we do is tell it to find `mybib.bib`

```
---
title: "Report Example"
output: bookdown::pdf_document2
bibliography: "mybib.bib"
---
```

## Desirable styles, etc

We decided to also use the `natbib` package and ASA's style guide with has us add:

```
---
title: "Report Example"
author: ""
output:
  bookdown::pdf_document2:
    citation_package: natbib
bibliography: "mybib.bib"
csl: "https://github.com/citation-style-language/styles/blob/master/american-statistical-association.csl"
---
```

## Actually referencing documents

Just for easy of conversation, our `.bib` file has some lines that say:

```
@article{parker2003,
  title={Robert Parker Wine Advocate},
  author={Parker, Robert},
  journal={The Wine Advocate, Inc},
  address={Napa},
  year={2003}
}

```

To cite the documents we can use `\@label` or `[\@label]` to get a text based one or a paranthesis based one. For example: @parker2003, [@parker2003]. You can also do [e.g. @parker2003, pg 2] (or one of the two). All of these citations will link us to the reference's section at the end of this document.

# Code Appendix

For some documents you still want to have all the code but you want to keep it in a code appendix at the end. 

1. Note that we have some comments run off the page. To avoid this make sure you obey and 80 character limit in your code. You can make a line in your Rstudio to show the 80 character line. This can be found from this path:

```
Rstudio > Preferences > Code > Show Margin 
```

If you put the following code block in your code you'll get all the code chucks pasted together. (notice I also like seperating the code appendix with a `\pagebreak`)

````markdown
`r ''````{r ref.label=knitr::all_labels(), echo = T, eval = F}
```
````

\pagebreak


```{r ref.label=knitr::all_labels(), echo = T, eval = F}
```