R markdown creates interactive reports from R code. This recitation is an introduction to basic R Markdown commands. For further R Markdown basics, please refer to this page and this cheat sheet.

Installing Latex on Your Computer

To produce PDF outputs, you will need to install a Latex compiler on your computer. If you are using Windows, you should install MikTeX for Windows and MacTex for Mac computers.

Document formating

You will be asked to produce a pdf output for your assignments and papers. If you are asked to produce an html output, make sure to have html_document under output:

---
title: "A Premier on R Markdown"
author: "Ömer Faruk Örsün | omerorsun@nyu.edu"
date: "September XX, 202X"
output:
  html_document:
    fig_caption: true
---

# Title
  
## A subtitle
### Another subtitle
      
# Another title

If you need to produce a pdf file, you will need to replace html_document with pdf_document. You should always use pdf_document for your assignments when submitting them. If you knit a file in .pdf format and notice that a line of code runs off the page, try splitting it into multiple lines. R does not see the end of a line as necessarily the end of a command. It looks for matching parentheses. So when it sees function(, it thinks that you’re continuing to add arguments to the function until it sees `). The code for any individual argument needs to be intact, but multiple arguments can be split across as many lines as you need.

Text formating


R markdown allows to easily format your text. You can add links, write in bold or italic. This is very well explained in the Rstudio cheatsheet. We can make the text italic using or bold or both bold and italic.

Here is the code I used to make this paragraph:

R markdown allows to easily format your text. You can add [links](www.r-graph-gallery.com), write in **bold** or *italic*. This is very well explained in the [Rstudio cheatsheet](https://github.com/rstudio/cheatsheets/raw/master/rmarkdown-2.0.pdf). We can make the text *italic* using  or **bold** or both ***bold and italic***.

R Codes, Outputs, Messages, Warnings

Here is where we would write our regular text. Note that we do not need to put it in comment notation, because text is the default in R Markdown. Code is something special, which is why we need to tell R Markdown specifically what is code, as to opposed to what is not.

We use the following format to introduce R codes. The following code sets the working directory for R so that it knows where the files I will call are stored.

#```{r chuncksettings, echo = TRUE, eval=TRUE, message=FALSE, warning=FALSE}
setwd("~/Dropbox/Data Analysis F20/Recitation Content/Recitation 2")

Here

  • echo = FALSE would prevent printing of the R code.
  • eval=FALSE would be added to the code to prevent running the code.
  • Similarly, message=FALSE and warning=FALSE would prevent showing messages and warnings associated with your code.

For homework assignments, you typically want to show your code. For full papers you typically do not.

In this example, what combination did I use?

Include and center an image


To center an image, use this code:

<center>
![My Plot Caption is here](Figure.jpeg){width=75%}
</center>

Here is the result

My Plot Caption is here

Include Figures


Specify the caption of your figure in the chunk header. Example:

#```{r, out.width ='60%', message=FALSE, warning=FALSE, fig.align="center", fig.width=6, fig.height=6, fig.cap="Here is a really important caption."}
#let's load some data
install.packages(tidyverse)
library(tidyverse)
Auto=read.csv("Auto.csv",header=T,na.strings="?")
attach(Auto)
ggplot(data=Auto)+
  geom_point(aes(x=horsepower, y=weight), color="red")
Here is a really important caption.

Here is a really important caption.

Note that R Markdown will put figures, tables, etc. (in LaTeX terms, these are called “floats”) wherever it thinks looks best.

Include Tables

You can create a table by

| Tables        | Are           | Cool  |
| ------------- |---------------| ------|
| col 3 is      | 1             | $1600 |
| col 2 is      | 3p3l4         |   $12 |
| zebra stripes | 2             |    $1 |

to produce

Tables Are Cool
col 3 is 1 $1600
col 2 is 3p3l4 $12
zebra stripes 2 $1

You can use the kable() function from the knitr package to format tables. The table captions are placed in the margin like figures in the HTML output. A simple example:

knitr::kable(
 mtcars[1:6, 1:6], caption = 'Table 1: XYZ'
)
Table 1: XYZ
mpg cyl disp hp drat wt
Mazda RX4 21.0 6 160 110 3.90 2.620
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875
Datsun 710 22.8 4 108 93 3.85 2.320
Hornet 4 Drive 21.4 6 258 110 3.08 3.215
Hornet Sportabout 18.7 8 360 175 3.15 3.440
Valiant 18.1 6 225 105 2.76 3.460

or

As an alternative, explore DT package.

library(DT)
datatable(mtcars, rownames = TRUE, filter="top", options = list(pageLength = 6, scrollX=T) )

or

We will explore stargazer package next week.

Writing Equations

Writing equations in R Markdown utilizes LaTeX formatting.

If you want to write some math in the middle of a line, \(\sum_{i=1}^n X_i\) you put it between two dollars signs and write the code in between. As you can see in this example, sometimes math formatting can get a bit squished when forced to be in line with the rest of the text. To set math apart, put it between two dollar signs, like so:

\[\sum_{i=1}^n X_i\]

Notice how as soon as you typed that last part, the equation appeared in your .rmd file. RStudio does this as a preview, so that you can see your equation without having to constantly knit and check it over and over. For a good introduction on writing math into an R Markdown document, see here:

If you scroll about half way down the page, that’s where the math formatting starts. You’ll need more than this in the long run, but this is an easily accessible first resource. After a little practice, I’m sure that you will find this to be WAY easier than inputting equations into Word.

Finally, while R Markdown does not underline your spelling mistakes the way that Word does, there is a spell checker. Go to Edit –> check spelling. You can check smaller components of your manuscript by highlighting the section of text and doing the same.

More on Basics

Headers and Lists

# Text for first level headers
## Text for second level headers
### Text  for third level headers

produces

Text for first level headers

Text for second level headers

Text for third level headers

Unordered List

* hello
* world
* this
    + is
    + NYUAD

produces

  • hello
  • world
  • this
    • is
    • NYUAD

make sure to have an empty space before and after the bullet lists. Otherwise, your text will not appear as a list.

We can have numbered lists as well:

1. hello
2. world
3. this
    * a bullet point
    - a bullet point
    + still a bullet point
4. NYUAD

produces

  1. hello
  2. world
  3. this
    • a bullet point
    • a bullet point
    • still a bullet point
  4. NYUAD

Resolving Problems in TeX Distribution and Creating PDF Outputs:

If you get TeX errors in creating PDF documents from your RMarkdown, here are some instructions: Include latex_engine : pdflatex in your YAML as in the following example:

---
title: "A Premier on R Markdown"
author: "Ömer Faruk Örsün | omerorsun@nyu.edu"
date: "September XX, 202X"
output:
  pdf_document :
    latex_engine : pdflatex
---

This should resolve the PDF creation issue. If it does not, then follow the instructions below. Since MacTex (Mac) or MikTeX (Windows) did not work in your case, you will need to uninstall them and instead install TinyTex.

  1. Close your R, R studio
  2. Uninstall the existing TeX programs [MacTex (Mac) or MikTeX (Windows)]
  3. Open RStudio and install the R package tinytex and then install TinyTex as the TeX distribution (install_tinytex()) :
install.packages('tinytex')
tinytex::install_tinytex()

Please note that this will take some time and may ask system administrator permissions.

  1. Close you RStudio
  2. Start Your RStudio and compile a PDF document in RMarkdown.
  3. If you successfully knit the PDF file, you are all set.
  4. If you still receive an error, include pdflatex in your YAML as in the following example:
---
title: "A Premier on R Markdown"
author: "Ömer Faruk Örsün | omerorsun@nyu.edu"
date: "September XX, 202X"
output:
  pdf_document :
    latex_engine : pdflatex
---

Note that you may get the TeX errors due to various reasons. For example, if the functions in RMarkdown or any of these latex distributions are updated, they sometimes lose their harmony and lead to problems in generating the PDF outputs. As a result, you may get a missing xxxx.sty error or hundreds of other errors. For example, you can see the types of problems people face in the following link and they are still not resolved by the package authors: https://github.com/yihui/tinytex/issues . Check both open and closed issues. You can also see the FAQ page: https://yihui.org/tinytex/faq/ Until your issue is resolved, you can submit your assignments in the HTML format. (edited)