Skip to main content

Lab session 6


This practical uses the following packages: dplyr, knitr, htmlTable

Main Practical

  1. Create a new folder for this practical. Download aspirin.csv from the course website and put it in this folder. In RStudio, create a new project from the folder you created. Create a new (empty) R markdown file in RStudio and save as “Outputs.Rmd” in the project folder.

    Set the options for knitr as follows, so that code, warnings and messages do not show in your output.

    knitr::opts_chunk$set(echo = FALSE, warn = FALSE,
                          message = FALSE)        
  2. In an R chunk, import the aspirin.csv data. This data is the same as that shown in the lecture, but with the levels of sex and condition already tidied up.

    Use functions from dplyr to create a tibble named x with the count, mean and standard deviation of value by sex and condition (as in the simple summary table on slide 19 or 20). Use ungroup to ungroup the tibble at the end.

    Use kable from knitr to create a table from x, using the digits and col.names arguments to customise the table as in the slides.

    Knit the document to create an HTML document containing just this table.

  3. We will use the htmlTable function from htmlTable to create booktabs style tables that we can later copy to Word. The following code creates a basic htmlTable based on the data frame x.

    lr <- c("l", "l", "r", "r", "r")
              rnames = FALSE,
              align = lr, align.header = lr, 
              header = c("Sex", "Condition", "N", "Mean", "SD"),
              caption = "Table 1: A htmlTable table.")        

    The argument rnames = FALSE means that row numbers are not included in the table.

    Look at the help for txtRound from the htmlTable package to find out how to format x so that the columns have the same number of decimal places as the kable table in question 2.

    Add this table to your markdown file and knit your document to see the new table.

  4. htmlTable can also create tables with grouped rows, grouped columns and/or a formatted total row. For example, the rows could be grouped by sex as follows:

    lr <- c("l", "r", "r", "r")
    htmlTable(txtRound(select(x, -sex), digits = c(rep(0, 2), 1, 2)),
              align = lr,
              rgroup = c("Female", "Male"),
              n.rgroup = c(2, 2))        

    Here we use select to remove the sex variable from x - note this will not work if x is grouped by sex.

    Add this table to your document, updating the header row and the caption.

  5. Now we will add a figure to the document. Create a boxplot of value by sex and condition. Suppress the x axis with xaxt = "n" and set the y axis label to “Value”.

    Add a custom axis as follows

    axis(1, at = 1:4, 
         labels = c("Female\nAspirin", "Male\nAspirin",
                    "Female\nPlacebo", "Male\nPlacebo"), 
         line = 0.5, tick = FALSE)        

    This adds a new line in the x axis labels and puts them a little lower down than the default.

    Add the options dev = "png", dpi = 600, to the R chunk creating the plot, so that it will be saved as a high resolution .png. Look up the chunk option fig.height, fig.width, out.height and out.width on and experiment with setting these to different values.

  6. Change the YAML of your markdown to

    title: title

    Note this requires the Gmisc package. Re-knit your document to see the difference it makes.

  7. Open Outputs.html in RStudio. Using Edit > Find search and replace all instances of the word “grey” with “black”. Click the “Preview” button to preview the html file.

  8. Download template.docx from the website. This is a Word template for the journal “Europhysics Letters”. Open this file in Word.

    Copy an htmlTable including its caption from the RStudio preview into the Word document. Change the font of the table and caption to match the body text. Put your cursor inside the table, go to the Layout menu and select .

    Within Word, use to insert the .png created when knitting your .Rmd. It will be in the Outputs_files subdirectory of the directory where you have saved Outputs.Rmd.

Extra time exercise

  1. Download references.bib and epl.csl from the course website. In the YAML header of Outputs.Rmd add the lines

    bibliography: references.bib
    csl: epl.csl        

    The in the body of the .Rmd and the lines

    # References        

    This cites two references from the BibTeX references.bib file. Re-knit Outputs.Rmd to obtain the references laid out in the journal style. The reference section can be copied to the Word document.

  2. Download the files epl2.cls, latex_example.Rmd, and header.tex. The latex_example.Rmd shows how a document class supplied by a journal can be used in a markdown file. The file header.tex contains the preamble from the example .tex file supplied by the journal - this contains fields such as \author{} that need to be filled in. This is also where packages such as booktabs can be loaded. In the body of the text LaTex is used as necessary, e.g. for referencing figures and tables. Otherwise, markdown can be used as normal.

    Try compiling latex_example.Rmd to produce the example PDF.