--- title: "R Markdown Sample" author: "Your Name" date: "1/8/2021" output: pdf_document: default html_document: df_print: paged editor_options: chunk_output_type: console --- **The original document of this file is provided by \href{http://jeromyanglim.blogspot.com/2012/05/getting-started-with-r-markdown-knitr.html}{Jeromy Anglim} and modified by Kenya Amano. Visit the \href{https://gist.github.com/jeromyanglim/2716336}{link} if you want to see the full version of this code.** This document examines the features of [R Markdown](http://www.rstudio.org/docs/authoring/using_markdown). This combination of tools provides an exciting improvement in usability for [reproducible analysis](http://stats.stackexchange.com/a/15006/183). Specifically, the document (1) discusses getting started with R Markdown and `knitr`; (2) provides a basic example of producing console output and plots using R Markdown; (3) highlights several code chunk options such as caching and controlling how input and output is displayed; (4) demonstrates use of standard Markdown notation as well as the extended features of formulas and tables; and This document was produced with R Markdown. It may be most useful if the source code and displayed post are viewed side by side. ## Getting started To work with R Markdown, if necessary: * Install [R](http://www.r-project.org/) * Install the lastest version of [RStudio](http://rstudio.org/download/) (at time of posting, this is 0.96) * Install the latest version of the `knitr` package: `install.packages("knitr")` To run the basic working example that produced this blog post: * Open R Studio, and go to File - New - R Markdown * If necessary install packages: Do `install.packages("PackageName") * Paste in the contents of this gist (which contains the R Markdown file used to produce this post) and save the file with an `.rmd` extension * Click Knit HTML To produce PDF file, you need TeX files. * Easy way: Install the `tinytex` package: `install.packages("tinytex")`. Then run `tinytex::install_tinytex()`. * If you want full version of TeX: For Mac install [MacTeX](http://www.tug.org/mactex/downloading.html). For Windows install [TeX Live](http://tug.org/texlive/acquire-netinstall.html). * More info: [R Markdown Reference Guide](https://rstudio.com/wp-content/uploads/2015/03/rmarkdown-reference.pdf) [R Markdown Cheat Sheet](https://rstudio.com/wp-content/uploads/2015/02/rmarkdown-cheatsheet.pdf) \newpage ## Prepare for analyses ```{r, warning=FALSE, message=FALSE} set.seed(1234) #install.packages("tidyverse") #install.packages("lattice") #install.packages("stargazer") #install.packages("pander") #install.packages("kableExtra") library(tidyverse) library(lattice) library(stargazer) library(pander) library(kableExtra) ``` Without specify the options of chunk, you get *warning* ## Basic console output To insert an R code chunk, you can type it manually or just press `Chunks - Insert chunks` or use the shortcut key. This will produce the following code chunk: ```{r} ``` Pressing tab when inside the braces will bring up code chunk options. The following R code chunk labelled `basicconsole` is as follows: ```{r } x <- 1:10 y <- round(rnorm(10, x, 1), 2) df <- data.frame(x, y) df ``` The code chunk input and output is then displayed as follows: ```{r basicconsole, warning = FALSE} x <- 1:10 y <- round(rnorm(10, x, 1), 2) df <- data.frame(x, y) df ``` ```{r basssss, warning = FALSE} x <- 1:10 y <- round(rnorm(10, x, 1), 2) df <- data.frame(x, y) df ``` ```{r basiole, warning = FALSE} x <- 1:10 y <- round(rnorm(10, x, 1), 2) df <- data.frame(x, y) df ``` \newpage ## R Code chunk features ### Create Markdown code from R Frequently used chunk options Option | Description - | ----- include | If FALSE, knitr will run the chunk but not include the chunk in the final document echo | If FALSE, knitr will not display the code in the code chunk above it’s results in the final document. error | If FALSE, knitr will not display any error messages generated by the code. message | If FALSE, knitr will not display any messages generated by the code. warning | If FALSE, knitr will not display any warning messages generated by the code. Recommendation for Homework Option | HW setting --- | --- include | TRUE | echo | TRUE | error | FALSE | message | FALSE | warning | FALSE | ### Echo and Results The following code hides the command input (i.e., `echo=FALSE`), and outputs the content directly as code (i.e., `results=asis`). ```{r dotpointprint, results='asis', echo=FALSE} cat("Here are some dot points\n\n") cat(paste("* The value of y[", 1:3, "] is ", y[1:3], sep="", collapse="\n")) ``` This code includes the command input (i.e., `echo=TRUE`) with markup output (i.e., results -> default ) ```{r dotpointprint2, echo=T} cat(paste("* The value of y[", 1:3, "] is ", y[1:3], sep="", collapse="\n")) ``` You can also write the result here with *sigle quote* r object *sigle quote* : The value of y[1] is `r y[1]`. ### Message and Warning While the chunk without specification of options show all wanings and messages.... ```{r} df %>% summarize_at(vars(y), funs(mean)) ``` this code does not output warnings ```{r, warning=FALSE} df %>% summarize_at(vars(y), funs(mean)) ``` ### Cache analysis Caching analyses is straightforward. Here's example code. On the first run on my computer, this took about 10 seconds. On subsequent runs, this code was not run. If you want to rerun cached code chunks, just [delete the contents of the `cache` folder](http://stackoverflow.com/a/10629121/180892) ```{r , cache=TRUE} for (i in 1:5000) { lm((i+1)~i) } ``` \newpage ## Basic markdown functionality For those not familiar with standard [Markdown](http://daringfireball.net/projects/markdown/), the following may be useful. See the source code for how to produce such points. However, RStudio does include a Markdown quick reference button that adequatly covers this material. ### Dot Points Simple dot points: * Point 1 * Point 2 * Point 3 and numeric dot points: 1. Number 1 2. Number 2 3. Number 3 and nested dot points: * A * A.1 * A.2 * B * B.1 * B.2 ### Equations Equations are included by using LaTeX notation and including them either between single dollar signs (inline equations) or double dollar signs (displayed equations). If you hang around the Q&A site [CrossValidated](http://stats.stackexchange.com) you'll be familiar with this idea. There are inline equations such as $y_i = \alpha + \beta x_i + e_i$. And displayed formulas: $$\frac{1}{1+\exp(-x)}$$ $$ x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} $$ $$ \begin{split} X & = (x+a)(x-b) \\ & = x(x-b) + a(x-b) \\ & = x^2 + x(a-b) - ab \end{split} $$ More info: [LaTeX wiki](https://en.wikibooks.org/wiki/LaTeX/Mathematics) ### Tables Tables can be included using the following notation A | B | C --- | --- | --- 1 | Male | Blue 2 | Female | Pink Or you want to show nice regression tables ```{r} Mod1 <- y ~ x Res1 <- lm(formula = Mod1, data = df) Mod2 <- y ~ x^2 Res2 <- lm(formula = Mod2, data = df) ``` ```{r, results='asis'} stargazer(Res1, Res2) #For html #stargazer(Res1, Res2, type = "html") ``` More info: [Cheat Sheet](https://www.jakeruss.com/cheatsheets/stargazer/) If you want to create a fancy table from data.frame, you can use "pander" or "kable" ```{r} Table <- df %>% mutate(z = if_else(y>5, 1, 0)) %>% t() Table ``` With `pander` ```{r} Table %>% pander(caption ="Fancy Table") ``` With `kable` ```{r} Table %>% kableExtra::kable() ``` ### Plots You can also show plots ```{r} df %>% ggplot(aes(x = x, y = y))+ geom_point()+ geom_smooth(method = "lm", formula = y ~ x)+ labs(title = "Sample Plot", y = "Happiness", x = "Exam score")+ theme_bw() ``` ### Images Images can be called using *include_graphics*. ```{r, echo = T, out.width='85%', fig.align='center'} knitr::include_graphics("C:/Users/ak915/git/MethodRA/terry-schiavo-misleading-graph.jpg") ``` Source: Statistics How To "\href{https://www.statisticshowto.com/misleading-graphs/}{Misleading Graphs: Real Life Examples}"