Novartis / xgx

Exploratory Graphics for PKPD data
26 stars 9 forks source link

Create Rmarkdown Tips page #51

Open iamstein opened 1 year ago

iamstein commented 1 year ago

There are lots of little tips I find and always forget and thought it'd be nice to compile them in a page. It could be another Resource. Pasting a bit of it below to give you an idea.


title: Rmarkdown Tips author: "Andy Stein" date: "r format(Sys.time(), '%d %B, %Y')" output: bookdown::html_document2: toc: yes toc_float: yes code_folding: hide bibliography: Bibliography.bib

Common Errors

Header - Default

---
title: YOUR TITLE
author: "YOUR NAME"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
  bookdown::html_document2:
    toc: yes
    toc_float: yes
    code_folding: hide
bibliography: Bibliography.bib
---

Text

Displaying messages and warnings by default

knitr::opts_chunk$set(warning = FALSE, message = FALSE)

Number of digits to display in inline code by default

knitr::knit_hooks$set(inline = function(x) {
  x <- sprintf("%1.2", x)
  paste(x, collapse = ", ")
})

Figures

Set default size

knitr::opts_chunk$set(fig.height = 4, fig.width = 8)

How to cross-reference and add caption

Tables

data.table vs kable

Set default number of rows

Change number of rows

How to cross-reference and add caption

References


set.seed(123)

#set chunk default options
knitr::opts_chunk$set(warning = FALSE, message = FALSE, fig.height = 4, fig.width = 8)

# Output only 2 significant digits for inline r outputs
knitr::knit_hooks$set(inline = function(x) {
  x <- sprintf("%1.2g", x)
  paste(x, collapse = ", ")
})
iamstein commented 1 year ago

For adding a caption, this is my favorite code now:

Rmd_name = "Rmd_Name.Rmd"
caption = paste(c("Rmd_Directory", 
                  Rmd_name,
                  str_replace(Rmd_name, ".Rmd$", ".html"),
                  paste(Sys.time())),
                  collapse = "\n")
ggcaption = list(labs(caption = caption),
                 theme(plot.caption = element_text(hjust = 0.5)))

Then, later on in the code, I can just write:
g = g + ggcaption