In this practical you’ll practice creating interactive reports using RMarkdown.
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
File | Rows | Columns |
---|---|---|
trial_act.csv |
2139 | 27 |
Open your class project. In your 1_Data
folder, make sure you have copies of the datasets listed above.
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
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
Now knit your document to an HTML file. To do this, click the knit button (or use the Command + Shift + K shortcut)
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
Knit your document! Make sure you see an output!
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
.
Knit the document to make sure it worked! If you have any errors, try to figure out how to solve them!
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
.
Knit the document! Diagnose and correct any errors!
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.
Knit the document! Diagnose and correct any errors!
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")
Knit the document! Diagnose and correct any errors!
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")
Knit the document! Diagnose and correct any errors!
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()
Knit the document! Diagnose and correct any errors!
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
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
).
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!
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?!
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 = "../")
Knit your document! Did everything work? If not, try to correct the working directory issues. Don’t be afraid to ask for help!
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 :)
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.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')
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.
You should see a new .Rmd document open. Save the document in your main project directory as slideshow.Rmd
.
Knit the document to see the outline of the presentation!
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()
.
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.
Want to see the .Rmd file that created this practical? You can find it here.
The rmdformats
package has many nice templates for .Rmd files. Look at their GitHub page at https://github.com/juba/rmdformats for examples. If you install the package from CRAN with install.packages('rmdformats')
, you’ll get lots of new templates when you open a new Markdown file in RStudio.
If you want to use custom .css files, check out the the R Studio HTML document guide. You can also look at the .css files underlying the rmdformats
package on their GitHub page here https://github.com/juba/rmdformats. For example, here is their .css file for the “html docco” template https://raw.githubusercontent.com/juba/rmdformats/master/inst/templates/html_docco/docco.css