Where to store different settings in Rmarkdown files

R tricks Rmarkdown R programming

This may be of use to others but it’s partly for me as I keep forgetting these and searching around for the .Rmd files in which I used the one I want!

Chris Evans https://www.psyctc.org/R_blog/ (PSYCTC.org)https://www.psyctc.org/psyctc/
2021-02-28
Show code
### this is just the code that creates the "copy to clipboard" function in the code blocks
htmltools::tagList(
  xaringanExtra::use_clipboard(
    button_text = "<i class=\"fa fa-clone fa-2x\" style=\"color: #301e64\"></i>",
    success_text = "<i class=\"fa fa-check fa-2x\" style=\"color: #90BE6D\"></i>",
    error_text = "<i class=\"fa fa-times fa-2x\" style=\"color: #F94144\"></i>"
  ),
  rmarkdown::html_dependency_font_awesome()
)

Updated with improved information about ggplot defaults 25.x.21

Rmarkdown is brilliant as a framework in which to create reports using R and it’s often useful to reset various defaults at the start of a file. Increasingly I work from Rmarkdown to html so some of this only applies there. I find there are three places I set things:

Setttings in the yaml header

This is well documented in many places and https://bookdown.org/yihui/rmarkdown/html-document.html is probably the canonical reference but searching will provide much other advice. I often use:

---
title: "A title here"
author: "Xxxx Yxxx"
date: "03/01/2021"

output:
  html_document:
    toc: true
    toc_float: true
    toc_depth: 4
    fig_height: 8
    fig_width: 11    
# bibliography: references.bib
---

I think the main things to say about that is that I don’t find that the floating table of contents (toc_float: true) always works, with long documents and complex blocks with graphics and text I find it sometimes mangles the toc so I am using it less than I used to. This can be a useful place to set the figure heading if they might be the same for all your code blocks with graphic output. I am not sure how many other code block header settings you could set here. I must experiment more: could save me a lot of typing. The only other thing there is the bibliography line, commented out. I still haven’t got into regular use of the citation and referencing capacities built into Rmarkdown. Must try harder!

Here is another

---
title: "ICCs from multilevel models analysed with lme4 or nlmer"
author: "CE"
date: "26/02/2021"
output:
  html_document:
    # css: "test.css"
    toc: TRUE
    toc_float: FALSE
    dpi: 200
    out.width: "100%"
    fig.height: 40
---

That shows that you can call an external css file (see next section), so far I haven’t found that I have enough css to make that worth doing. More important here, and I’m still working on this, I have found that you can use out.width: "100%" to make the html avail itself of more of your screen width which I find useful. The dpi: 200 and huge fig.height: 40 settings were me trying to optimise my graphic output for some complex plots.

for xelatex if using PDF and flextable

[added 1.xi.23]

In the last few months my long, long search for a single Rmarkdown (and now, tidyverse) compatible table generating package has sort of settled on flextable. It’s not perfect but for the moment at least it’s doing most of what I want. However, today, for the first in ages, I wanted to output to PDF and hit an issue which is that flextable really wants the xelatex PDF writer not the default (I forget what that is). So I installed xelatex (this is just to remind myself):

apt install texlive-xetex
# or
apt-get install texlive-xetex
# or
sudo apt install texlive-xetex
# if you're not in a root console session so also:
sudo apt-get install texlive-xetex

Now the yaml I need is

---
title: "Setswana forward translations"
author: "Chris Evans"
date: "2023-11-01"
output:
  pdf_document:
    latex_engine: xelatex
---

I’m putting this here really just to remind myself of the indentation/nesting there.

yaml heading settings for distill

… in index.Rmd

This is all I have in my index.Rmd file. As yet I haven’t found any other options that can usefully be added here.

---
title: "An R SAFAQ by Chris Evans"
site: distill::distill_website
listing: posts
---

… in “posts”

This where most of the Distill extensions to routine Rmarkdown yaml header blocks go. Here’s an example.

---
title: "Making the CECPfuns package: my own usable package"
description: |
  This is very much work in progress so look for later posts about CECPfuns as well as this.
base_url: https://www.xxxx.org/psyctc/Rblog/  
preview: https://www.xxxx.org/pelerinage2016/wp-content/uploads/2020/07/P1160474.jpg
author:
  - name: Xxxx Yyyy
    url: https://www.xxxx.org/R_blog/
    affiliation: xxxx.org
    affiliation_url: https://www.xxxx.org/psyctc/
    orcid_id: xxxx-xxxx-xxxx-xxxx

date: 2021-02-10
output:
  distill::distill_article:
    toc: true
    toc_depth: 4
    hightlight_downlit: true
    self_contained: false
    code_folding: true
creative_commons: CC BY-SA
---

I think that’s mostly self-explanatory and I hope I’ve messed up my own data with sufficient “xxxx” insertions that it’s safe for people to copy and paste to create their own extension on the basic yaml that distill:create_post("post title") creates. The code_folding option means that blocks of code are “folded” away by default but have a “Show code” button so the reader can unfold the code and read it.

… in articles/pages

Here is one of my yaml headers:

---
title: "Welcome to these pages"
description: |
  Welcome to these pages which I hope will be useful to people using R to analyse data.
base_url: https://www.xxx.org/psyctc/Rblog/  
author:
  - name: Xxxx Yyyy
    url: https://www.xxx.org/R_blog/
    affiliation: Xxxx.org
    affiliation_url: https://www.xxx.org/psyctc/
    orcid_id: xxxx-xxxx-xxxx-xxxx
date: "2024-04-14"
output: 
  distill::distill_article:
    self_contained: false
creative_commons: CC BY-SA    
---

I think that’s all pretty self-explanatory. I am sure you can see what to if copying and pasting this!

Settings in css block

CSS is definitely not my expert area but I have been using a block like this:

click to show css_chunk.txt

(Apologies for this way of putting the code in here: I gave up on trying to work out how to escape characters or otherwise override things being mangled in knitting that!)

That is using the principles behind css (cascading style sheet) to set some html defaults. The first two stanzas allow raw R text output (which comes out in the html “pre” format) to come up in a horizontally scrollable window which can be useful where you find you are spitting out wide output and the next stanza I think determines the formatting of raw code (not sure about that!).

The body stanza is a recent discovery of mine. The “body” section of html is everything except the header information, i.e. it’s what the human reading an html document sees. That allows my html output to use more of my nice big screen.

Settings in early/first R code block

When you create a new Rmd file in Rstudio it always has this first R code block.

click to show default_setup_chunk.txt

I often expand that to something like this:

click to show big_setup_chunk.txt

[updated 5.xi.23] Perhaps most usefully, I realised that I can set my default Rmarkdown block settings, e.g.

knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE, fig.width = 16, fig.height = 12, cache = FALSE)

rather than the default setting:

knitr::opts_chunk$set(echo = TRUE)

Setting ggplot defaults

[updated 25.x.21] I have my own preferences for some of the “theme” elements in ggplot and discovered that I can set these for a whole Rmarkdown files like this:

### set ggplot defaults
theme_set(theme_bw())
theme_update(plot.title = element_text(hjust = .5),
             plot.subtitle = element_text(hjust = .5))

That theme_set() sets the default theme that will be used by ggplot() for the rest of the session, here I have set it to theme_bw() and then the theme_update() updates that. You can also make that a named object

### save whatever the current theme settings are to an object
theme_get() -> CEtheme

Which can make it easy to reinstate it with theme_set(CEtheme). And, of course, if you wanted to, you could even save that to a tiny file:

### set ggplot defaults to file
save(CEtheme, "CEtheme")

So in any other R work you can load() that file and set theme.

load(file = "CEtheme")
oldTheme <- theme_set(CEtheme) # uses invisible return of the pre-existing default theme by theme_set() to save that 

Do contact me if you have advice about setting Rmarkdown options and if have corrections to the above.

Visit count

page counter

Last updated

Show code
cat(paste(format(Sys.time(), "%d/%m/%Y"), "at", format(Sys.time(), "%H:%M")))
14/04/2024 at 09:16

Reuse

Text and figures are licensed under Creative Commons Attribution CC BY-SA 4.0. The figures that have been reused from other sources don't fall under this license and can be recognized by a note in their caption: "Figure from ...".

Citation

For attribution, please cite this work as

Evans (2021, Feb. 28). Chris (Evans) R SAFAQ: Where to store different settings in Rmarkdown files. Retrieved from https://www.psyctc.org/R_blog/posts/2021-02-28-where-to-store-different-settings-in-rmarkdown-files/

BibTeX citation

@misc{evans2021where,
  author = {Evans, Chris},
  title = {Chris (Evans) R SAFAQ: Where to store different settings in Rmarkdown files},
  url = {https://www.psyctc.org/R_blog/posts/2021-02-28-where-to-store-different-settings-in-rmarkdown-files/},
  year = {2021}
}