Source: https://www.rstudio.com/

Source: https://www.rstudio.com/

Overview

In this practical you’ll practice creating interactive reports using RMarkdown.

Cheatsheet

If you don’t have it already, you can access the Markdown cheatsheet here https://www.rstudio.com/wp-content/uploads/2015/03/rmarkdown-reference.pdf

Datasets

File Rows Columns
trial_act.csv 2139 27

Tasks

  1. Open your class project. In your 1_Data folder, make sure you have copies of the datasets listed above.

  2. Because R Markdown looks quite a bit different from standard R code, the best way to look at examples is to see a new R Markdown document in action. In RStudio, click File – New File – R Markdown

  1. Give the document a title and an author. For the output format, select HTML (the default). Click Ok!

  1. A new file that looks like this should open up. This is your first R Markdown document!

  1. Save your markdown file in your main project directory (not in the 4_Markdown folder! – you’ll put it there later!) under the name speffanalysis.Rmd

  2. Now knit your document to an HTML file. To do this, click the knit button (or use the Command + Shift + K shortcut)

  1. Now you should see your final, HTML document! Scroll up and down the document and see how she looks!

  1. In the first code chunk (with the label setup), include the following code: the arguments inknitr::opts_chunk$set() will set your global chunk options, while finally, options(digits = 2) makes sure that all of your numeric output is rounded to two decimal places.
# INCLUDE ALL OF THIS CODE IN YOUR FIRST CHUNK!

knitr::opts_chunk$set(fig.width = 6,        # Figure width (in)
                      fig.height = 6,       # Figure height (in)
                      echo = TRUE,          # Repeat code
                      eval = TRUE,          # Evaluate chunks
                      message = FALSE,      # Don't print messages
                      warning = FALSE,      # Don't print warnings
                      fig.align = 'center') # Center figures

options(digits = 2)  # Round all output to 2 digits
  1. Knit your document! Make sure you see an output!

  2. Now let’s load some packages. Inside your setup chunk, write the comment # Loading Packages -------------. Then, using the library() function, load the packages tidyverse, knitr and speff2trial.

  3. Knit the document to make sure it worked! If you have any errors, try to figure out how to solve them!

  4. It’s time to load your data! Inside of your setup chunk, load the trial_act.csv file with read_csv() and assign the result to the object trial_act.

  5. Knit the document! Diagnose and correct any errors!

  6. Add the necessary text and markdown to your document to create the following two paragraphs. Pay attention to the header sizes, italics and code formats.

Write the necessary markdown to create this output!

Write the necessary markdown to create this output!

  1. Knit the document! Diagnose and correct any errors!

  2. Add the appropriate combination of text, markdown, code chunks, and R code to add the following output to your document. To report the number of patients, use an in-line chunk to access the number directly from the data using the nrow() function, – that is, don’t type 2139 directly! To create the table, create a new chunk, and inside that chunk, use the kable() function, with the appropriate arguments, to create the table. The following code might help you create the table:

# Code for Table 1:

trial_act %>%
  select(pidnum, age, wtkg, hemo, homo) %>%
  select(1:5) %>%
  slice(1:5) %>%
  kable(caption = "Table 1: XXX")
  1. Knit the document! Diagnose and correct any errors!

  2. Write the necessary code to add the following output to your document. To do this, create a new chunk. In the chunk use dplyr code to create the summary table of data. Assign the result to the object trial_summary. Then, use kable() to render this dataframe as a table in the final document.

Here is some code you might find helpful in creating this table!

# Helpful code to create the summary table!

trial_act %>% 
    group_by(XX) %>% 
    summarise(N = n(),
              Mean = mean(XX),
              Median = median(XX),
              SD = sd(XX),
              Max = max(XX)) %>%
  kable(caption = "Table 2: XXX")
  1. Knit the document! Diagnose and correct any errors!

  2. Add the appropriate combination of text, markdown, code chunks, and R code to add the following output to your document. Be sure to include the figure caption (you can do this with the fig.cap argument to the chunk)

This code might help you to create the plot:

# Boxplot code template

ggplot(data = XX, 
       mapping = aes(x = factor(XX), y = XX)) +
  geom_boxplot() + 
  labs(x = "XX",
       y = "XX",
       title = "XX",
       subtitle = "XX",
       caption = "XX") + 
  theme_bw()
  1. Knit the document! Diagnose and correct any errors!

  2. A researcher wants to know if there is a correlation between patients’ CD4 T cell count at baseline (cd40) and the number of days until a major negative event. Include this information as a new subsection (with a second level header) in your analyses. To do this, run the following chunk. Then, write a sentence with the main outputs from the test, using inline chunks to directly access the correlation and the p-value. For example, a sentence could be: “The correlation between CD4 T cell count at baseline and number of days until a major negative event was r = XX, p = YY”.

# Correlation test between cd40 and days

cd4_cor <- cor.test(formula = ~ XX + XX,
                    data = XX)

cd4_cor_r <- cd4_cor$XX  # Get the correlation
cd4_cor_p <- cd4_cor$XX   # Get the p-value
  1. In addition to the correlation test, include a relevant scatterplot showing the relationship between CD4 T cell count at baseline (cd40) and number of days until a major negative event (days).

  2. Add a new section called “Conclusions”. Write the main conclusions of your analyses in one or two sentences. Feel free to add some formatting and/or in-line chunks to your content!

Managing working directories with Markdown

  1. Now it’s time to move your Markdown file to your 4_Markdown folder. Move your speffanalysis.Rmd file to your 4_Markdown folder using your computer file browser (Finder on Mac, Windows explorer on PC). Now, try knitting your document. You should get an error! What happened?!

  2. The problem is that when you knit your Markdown file, R changes your working directory to the folder where your markdown file is located. However, now that you moved your file to your 4_Markdown folder, this isn’t true anymore. You need to tell Markdown that the root directory of your project is one directory up! Thankfully this is easy to do. Just add the following code to your initial setup R chunk:

# Tell R Markdown that the root directory is now one folder
#   up from the folder the markdown file is in

knitr::opts_knit$set(root.dir = "../")
  1. Knit your document! Did everything work? If not, try to correct the working directory issues. Don’t be afraid to ask for help!

  2. If you have LaTex installed on your computer, try knitting your document to PDF format by clicking the Knit button and knit to PDF. If you don’t have LaTeX installed, don’t worry :)

Other Markdown templates

  1. Don’t like the standard markdown template? You can get many other templates from the rmdformats package. Install the package with rmdformats. Then create a new markdown file from one of the temples with File – New File – R Markdown – From Template. Try the HTML readthedown template. Knit the document and see how it looks different from your standard template.

Slideshow

  1. Now it’s time to create a slideshow! To do this, we’ll use the Ninja template (click here for a demo) from the xaringan package (that’s what we use for all of our BaselRBootcamp slides). Install the xaringan package by running install.packages('xaringan')

  2. Once you’ve installed xaringan, open a new template with File – New File – R Markdown – From Template – Ninja Presentation. Give the presentation a title and your name as the author. Then click ok.

  3. You should see a new .Rmd document open. Save the document in your main project directory as slideshow.Rmd.

  4. Knit the document to see the outline of the presentation!

  5. Play around with the presentation a bit. Change the existing content a bit and add a few slides. Try adding an image (maybe this one: https://actgnetwork.org/sites/all/themes/actg/images/actg_logo_275.png) by saving the image to your 0_Materials folder, and then loading the image into your document with include_graphics().

  6. Now, try to customize the presentation to include all of main analyses, outputs, and plots you have in your speffanalysis.Rmd document! Of course, there won’t be room for all of the text, so treat it like a normal presentation and put in what’s important.