This lesson is still being designed and assembled (Pre-Alpha version)

Knitr Syntax: Styling Code Outputs

Overview

Teaching: 35 min
Exercises: 5 min
Questions
  • How do I make better styled tables in R Markdown?

  • How do I add captions to code generated figures?

  • How do I consistently size and align images and figures?

  • How do I cross reference figures & tables?

Objectives
  • Create better styled tables

  • Add captions to code-generated figures, tables, images

  • Globally size and align images and figures

  • Use cross referencing

Create better tables in R Markdown

Our markdown table is formatted weirdly after knitting. Unfortunately, it isn’t possible to style tables created with basic markdown syntax. In order to create a table that is stylable, we need to save it as a dataframe and use a package function to style it. There are MANY packages that allow you to create tables in Rmd. See list (https://bookdown.org/yihui/rmarkdown-cookbook/table-other.html)

Restyle the table with kable

We will use kable to recreate our table. kable() is a function in the knitr package. kable() creates a basic stylable table.

1) load data & package in load-data-libraries chunk:

```{r load-data-libraries}   
## ADD to existing libraries & data  
 
#load knitr for kable table
library(knitr)

###

#load table 1 data
table1 <- read_csv("../data/table.csv")` 

2) Delete the existing table (leave the caption for now)

3) create a new code chunk in place of the table, name it table-1 4) call kable() function on table1 dataframe

```{r table-1}   
kable(table1)  

Time to Knit!

Check to see if our table generated properly

your code chunk should output as so:

Category N
Poor sample quality from users/sample variability/limited biological material 51
Lack of well-trained principle investigators and lab members/Poor oversight 45
Poor experimental design: Lack of sufficient replicates/inadequate sample size/lack of adequate controls 43
Inadequate standardization of protocols or guidelines, and data analysis 43
Cost and time 39
Failure to leverage the core’s expertise/following the core’s advice/no consulting beforehand 23
Inadequate documentation of experiments/data management 19
Instruments: maintenance, upgrades, changes 15
Responses that could not be assigned to a category 11

Note: Styling kable tables

You can use the argument format to specify between html, latex, pipe, or rst styles. This can also be set in the global options with knitr.table.format. For additional styling, there is a function called kable_styling() to change the look of your kable tables. https://www.rdocumentation.org/packages/kableExtra/versions/1.3.1/topics/kable_styling

Note: Other table packages

Even though we can do a bit more styling with kable(), it’s still pretty basic. To do more complex tables, kableExtra package was developed. This especially allows more control over formatting. There are other multiple other packages as well that help with table formatting officer for Word and xtable are two examples. officer: https://www.rdocumentation.org/packages/officer/versions/0.3.15 https://bookdown.org/yihui/rmarkdown-cookbook/table-other.html

Note: Styling Kable tables

You can use the argument format to specify between html, latex, pipe, or rst styles. This can also be set in the global options with knitr.table.format. For additional styling, there is a function called kable_styling() to change the look of your kable tables. https://www.rdocumentation.org/packages/kableExtra/versions/1.3.1/topics/kable_styling

Add captions to code-generated tables & plots

Also, we learned how to add captions to images earlier on, but now, how do we add captions to the code-generated plots and the new table we just added? It is a little different between tables and code-generated plots/images.

Add captions to code-generated tables

Ok, let’s start with the table. The kable() function has an argument called caption.

1) cut the orignial table caption from it’s spot in the paper 2) add to the kable function caption = and paste the caption in between "s

caption="Table 1. Major challenges to rigor observed in shared resources"

code will look like so:

```{r table-1}   
kable(table1, caption="Table 1. Major challenges to rigor observed in shared resources")  

Time to Knit!

Did the caption output for Table 1?
Hint: it will appear above the table.

Add captions to code-generated plots, figures & images

To add captions for Figure 1 and 3 we’re going to go back to our favorite: code chunk options. Anytime after defining the code chunk name we can add the chunk option: fig.cap = (so either before or after the other options, order doesn’t matter). Notice that the syntax is slightly different than our other options but it has the same = . Instead of indicating TRUE/FALSE however, we can type our caption right after the = in quotes fig.cap = "". NOTE: we are adding this to the code chunk options, NOT as an argument to the code like for the table.

1) type in fig.cap = "" after the chunk label (and a comma) 2) paste or type in the caption
FIGURE 1 - Knowledge and awareness of the current NIH guidelines on rigor and reproducibility.

Your code chunk options should now look like this:

{r fig-1, fig.cap="FIGURE 1 - Knowledge and awareness of the current NIH guidelines on rigor and reproducibility."} #code for figure 1 here

Time to Knit!

Check to see if the caption for Figure 1 appeared

CHALLENGE 9.1 - add a caption for Figure 3

Add the caption to the code for Figure 3:
FIGURE 3 - Types of tools that cores would like to implement in their operations.

SOLUTION

{r fig-3, fig.cap="FIGURE 3 - Types of tools that cores would like to implement in their operations." }

Time to Knit!

Check to see if caption for Figure 3 appeared

Globally & Automatically align & size plots/figures

We changed the sizing of our images in a previous episode. However, instead of changing the sizes one-by one, we can do it within our knitr::opts_chunk$set settings in our setup code chunk.

Automatically size figures & images

We can size with a number of inches, percentage of the original image size, or pixels (in some cases). The default for inches is 7in height and width for code-generated figures, plots & images (knitr) versus it’s 5in height by 7in width for markdown generated images (rmarkdown).

There is no default for perentages because the default size is inches. When using percentages it’s important to note that % refers to the percent of the HTML container. So images are sized in relation to their original size, but in relation to the html document size. For example, if the block of text on a webpage is 1000px wide then resizing at 20% width means the image will be 200px in width.

Option options for resizing

Two options fig. and out.. out. is more expansize than fig. both in how size can be defined and what kind of figures/plots/images it can be applied to.

fig.width along with fig.height, ONLY applies to R-generated figures defined within a code chunk. It changes the width of the images based on the specifications which can be defined in inches & percentage.
fig.height along with fig.width, ONLY applies to R-generated figures defined within a code chunk. It changes the height of the images based on the specifications which can be defined in inches & percentage.

out.width along with out.height, can be applied to any type of graphic defined within a code chunk. It changes the width of the images based on the specifications which can be defined in inches, percentage & number of pixels.
out.height along with out.width, can be applied to any type of graphic defined within a code chunk. It changes the height of the images based on the specifications which can be defined in inches, percentage & number of pixels.

We want to be inclusive of the images in our Rmd file so we will use out.width & out.height which offers more flexibility. Also, we previously sized the images to 50%, but that was a bit small, so let’s try 60% instead.

Add to (before or after) the other options, in the global code chunk:

knitr::opts_chunk$set(out.width="60%", out.height="60%", echo = FALSE, message = FALSE, warning = FALSE)

Time to Knit!

See how our images re-sized.

Oh no, Fig 2 isn’t aligning! Unfortunately, the settings ONLY apply to knitr-rendered code chunks, but our Figure 2 is still just a rmarkdown-styled image.

We can add the Fig 2 .jpg to a code chunk instead:

1) create a new code chunk and name the it fig-2 2) copy and paste the caption between quotes with the fig.cap="" option. 3) use include_graphics() function from the knitr package (alternatively can use syntax knitr::include_graphics()) if you haven't loaded the package. 4) Add the file path in quotes between the () of include_graphics().

{r fig-2, eval = FALSE, echo = TRUE, fig.cap="FIGURE 2 - Lack of requests for rigor and reproducibility documentation by users of shared resources."} include_graphics("../figs/fig2_paper.jpg")

Time to Knit!

Check to see if all images re-sized

Automatically align code chunk outputs

To automatically & globally align code chunk outputs like we did with sizing, add to the setup code chunk:

fig.align = "center"

so the whole chunk will look like so:

knitr::opts_chunk$set(fig.align = "center", out.width="60%", out.height="60%", echo = FALSE, message = FALSE, warning = FALSE)

Time to Knit!

Check to see if all images and figures were aligned to the center

Cross-referencing (optional)

from bookdown.org:

Cross-referencing is a useful way of directing your readers through your document, and can be automatically done within R Markdown. While this has been explained in Chapter 2 from the bookdown book, we want to present a brief summary below.

To use cross-references, you will need:

After these conditions are met, we can make cross-references within the text using the syntax \@ref(type:label), where label is the chunk label and type is the environment being referenced (e.g. tab, fig, or eqn). An example is provided below:

We’ve already installed bookdown in our setup steps at the beginning of the workshop, but we need to make sure to load the bookdown library.

Add into your load-data-libraries code chunk:

#load bookdown for cross-referencing
library(bookdown)

We also need to change the output in the yaml to a bookdown specification so, change the output yaml in the yaml to the following(the rest stays the same.):

...
ouput:
  bookdown::html_document2:
...

Now to add cross referencing:

This is the syntax for a cross-reference link:

\@ref(type:label)

the \@ref will always remain the same. We will edit type and label

type options:

label is replaced with the chunk label of the code chunk figure/table/equation you want to link to.

Let’s try this out on our paper:

1) Find or search for the note: (See Table 1) in the Core Implementation section.

2) To add a cross reference link we will replace the “Table 1” text with:

\@ref(tab:table-1)

we will replace type with tab and label with table-1.

Time to Knit!

Check to see if the cross reference link for Table 1 appeared. Notice what happens when you click the link.

CHALLENGE 9.2: Add a Cross Reference to Figure 2

Search for or find in the text: “(See Figure 2)” in the “Strategies for Improving R&R sub section: Make this into a cross reference link.

SOLUTION

\@ref(fig:fig-2)

*Note adding crossing referencing re-names the figures, so should take the figure numbering out.

Time to Knit!

Check to see if the cross reference links appeared

Styling conclusions

There are a plethora of options for styling, from additional bookdown options, to things you can edit in the yaml (including adding themes to style text), and adding your own custom css style sheets. Explore more on your own!

Key Points

  • Use kable() to create tables from dataframes

  • add captions to figures and images generated by code chunks

  • Set global chunk settings to automatically size & align outputs

  • Use bookdown to enable cross referencing