Code chunk font size in Rmarkdown with knitr and latex

Picking up the idea to alter a knitr hook we can do the following:

def.chunk.hook  <- knitr::knit_hooks$get("chunk")
knitr::knit_hooks$set(chunk = function(x, options) {
  x <- def.chunk.hook(x, options)
  ifelse(options$size != "normalsize", paste0("\n \\", options$size,"\n\n", x, "\n\n \\normalsize"), x)
})

This snippet modifies the default chunk hook. It simply checks if the chunk option size is not equal to its default (normalsize) and if so, prepends the value of options$size to the output of the code chunk (including the source!) and appends \\normalsize in order to switch back.

So if you would add size="tiny" to a chunk, then all the output generated by this chunk will be printed that way.

All you have to do is to include this snippet at the beginning of your document.


\tiny

```{r}
summary(mtcars)
```
\normalsize

available options for size in descending order are:
Huge > huge > LARGE > Large > large > normalsize > small > footnotesize > scriptsize > tiny


Per this Gist, you have to define the font size using css:

<style type="text/css">
body, td {
   font-size: 14px;
}
code.r{
  font-size: 20px;
}
pre {
  font-size: 20px
}
</style>

code.r will control the font size for R code echoed from the code chunk, while pre will apply to any R results output from the code.

A complete working .Rmd file might look like:

---
title: "FontTest"
author: "Thomas Hopper"
date: "January 13,2016"
output: html_document
---

<style type="text/css">

body, td {
   font-size: 14px;
}
code.r{
  font-size: 20px;
}
pre {
  font-size: 20px
}
</style>

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r cars}
summary(cars)
```

The resulting html renders as:

screenshot showing 20pt R code and 20pt R output