Skip to content

Instantly share code, notes, and snippets.

@isteves
Last active May 14, 2020 12:54
Show Gist options
  • Save isteves/885706b0b05a914ef0d02c11a4194419 to your computer and use it in GitHub Desktop.
Save isteves/885706b0b05a914ef0d02c11a4194419 to your computer and use it in GitHub Desktop.
Useful Rmd snippets

Preferred YAML header:

---
title: My title
subtitle: My subtitle
author: My name
date: "`r Sys.Date()`"
output:
 html_document:
   toc: true
   toc_float: true
   toc_depth: 4
   theme: flatly
   highlight: tango
   code_download: true
   code_folding: hide
---

DT autowidth

Tables will not extend past the page width and will be scrollable instead.

without rownames

datatable(data, rownames = FALSE, width = "100%",
          options = list(autowidth = TRUE, scrollX = TRUE))

with rownames

datatable(data, width = "100%", options = list(autowidth = TRUE, scrollX = TRUE))

with specified height

datatable(width = "100%", height = "300px",
          fillContainer = TRUE, #this makes sure height restrictions are followed; w/o it, the tables overlap with the next section
          options = list(autowidth = TRUE, scrollX = TRUE, scrollY = "300px"))

knitr/kableExtra styling

kable() %>% kable_styling("striped")

autowidth

kable() %>% 
   kable_styling("striped", "condensed") %>% 
   scroll_box(width = "100%")

ggplot prettiness

Add +/- in title

+ labs(title = "Amount (\u00B1SE)")

widget tabsets with datatables + plots

for-loop

```{r include = FALSE}
iris_split <- split(iris, iris$Species)
list_of_plots <- map(iris_split, ~ggplot(.x, aes(Sepal.Length, Sepal.Width)) + geom_point())
list_of_tables <- map(iris_split, DT::datatable)
DT::datatable(NULL) # this is needed for JS? set-up
```

```{r results = 'asis'}
tabs_names <- names(list_of_plots)
tabs_n <- length(tabs_names)
for (i in 1:tabs_n){
   cat("###", tabs_names[i], "\n")
   print(list_of_plots[[i]]); cat(" \n\n")
   cat(knitr::knit_print(list_of_tables[[i]]))
   cat(" \n\n")
}
```

Source: rstudio/DT#67

Mapped version

Start with:

  • list of graphs
  • list of datatables

Steps:

  1. Create Rmd code chunk as character string
  2. Use map & paste/collapse to iterate over all tabs (one graph and one table per tab)
  3. Quietly knit the prepared character string of all Rmd code chunks
tabs_names <- names(list_of_graphs)
tabs_n <- length(tabs_names)

# can use knitr::knit_expand() or glue::glue() here for better readability
create_chunk_text <- function(n, tab_names, list_of_graphs, list_of_tables) {
   sprintf("#### %s\n\n```{r %s} \n print(%s[[%s]]) \n %s[[%s]] \n```\n\n", tab_names, 
           n, list_of_graphs, n, list_of_tables, n) 
}

all_chunks <- purrr::map_chr(1:tabs_n, create_chunk_text, tab_names, "list_of_graphs", "list_of_tables") %>%
    paste(collapse = "\n")

cat(knitr::knit(text = all_chunks, quiet = TRUE))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment