Code chunk font size in Rmarkdown with knitr and latex - r

In knitr, the size option works fine in a .Rnw file, the following code generates:
\documentclass{article}
\begin{document}
<<chunk1, size="huge">>=
summary(mtcars)
#
\end{document}
However, I can't get it to work in Rmarkdown. The following code does not change the font size, as it did in .rnw file. The same thing happens when trying to set options with opts_chunk$set(size="huge").
Is this the expected behavior? How does one change the chunk code font size? (I mean using knitr options, not by adding \huge before the code)
---
title: "Untitled"
output: pdf_document
---
```{r, size="huge"}
summary(mtcars)
```
I am using RStudio Version 0.98.987, knitr 1.6 and rmarkdown 0.2.68.

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:

You can define you own document format by exporting something based on the following function from your package my_package:
my_report <- function(...) {
fmt <- rmarkdown::pdf_document(...)
fmt$knitr$knit_hooks$size = function(before, options, envir) {
if (before) return(paste0("\n \\", options$size, "\n\n"))
else return("\n\n \\normalsize \n")
}
return(fmt)
}
This will define a knitr chunk hook size that will put the appropriate latex command before the chunk, and \normalsize after the chunk.
Anyway, with the following R markdown you can check if it's working:
---
output: my_package::my_report
---
Test text for comparison
```{r}
print(1)
```
The next code chunk has `size = 'tiny'` in the chunk options.
```{r, size = 'tiny'}
print(1)
```
I get the following result from `markdown::render():
See also the issue I opened on github:
https://github.com/yihui/knitr/issues/1296

Following up on #Martin Schmelzer's output, here's a solution in the case you want to change the code and output default font size for the whole document, but not the size of the text.
def.chunk.hook <- knitr::knit_hooks$get("chunk")
knitr::knit_hooks$set(chunk = function(x, options) {
x <- def.chunk.hook(x, options)
paste0("\n \\", "size_of_the_code_and_output","\n\n", x, "\n\n \\size_of_the_text")
})
For instance,
---
output: pdf_document
---
```{r setup, include=FALSE}
def.chunk.hook <- knitr::knit_hooks$get("chunk")
knitr::knit_hooks$set(chunk = function(x, options) {
x <- def.chunk.hook(x, options)
paste0("\n \\", "footnotesize","\n\n", x, "\n\n \\Huge")
})
```
# Section 1
```{r}
summary(cars)
```
Text.
# Section 2
```{r}
print(1)
```
This works for every chunks.
gives this:

Related

How can I adjust the style of the output from a .Rmd chunk?

Here is an example code chunk and it's output.
`{r example, message = F}
for (i in 1:5) {
print(i)
}
`
I would like this to render in my output file without the border box, and without the leading ## [1]. Is that possible?
This solution also removes the border box.
Use the r chunk comment option to remove the ## character.
Use cat() instead of print() to display the output without the R formatting [1]. You need to specify in cat() that you want newlines added.
One method to remove the border box would be to use css. You can use an external css file, or make a dedicated hidden chunk to specify it.
I noticed the code chunks and output chunks were both specified by the <pre> tag, with the code chunk being of class .r, and the output chunk being .hljs. These might change with different themes, but this selector worked for me. pre.hljs might work alternatively as a selector.
Below is a complete .Rmd file that can be knit to an html document
---
title: example.Rmd
output: html_document
---
```{css, echo = FALSE}
pre:not(.r) {
border: 0px;
}
```
```{r, comment = ""}
for (i in 1:5) {
cat(i, "\n")
}
```
Use the following code
{r example, message = FALSE, comment = ''}
for (i in 1:5) {
cat(i, '\n')
}

HTML page is left-aligned when specifying the theme to use ( R Markdown - cleanrmd package)

When using the cleanrmd package for R Markdown, the output html page is left-aligned if I specify the theme to use, while it's centered when the them is set as NULL.
theme set as NULL
---
title: "TEST"
output:
cleanrmd::html_document_clean:
theme: NULL
---
With a theme specified
---
title: "TEST"
output:
cleanrmd::html_document_clean:
theme: new.css
---
Anyone can help me to fix this?
Specify CSS rule body { margin: 0 auto; padding: 2rem;} for the entire body of the document, which will fix the issue.
---
title: "Title"
author: "Author"
date: "Date"
output:
cleanrmd::html_document_clean:
theme: new.css
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{css, echo = FALSE}
body {
margin: 0 auto;
max-width: 750px;
padding: 2rem;
}
```
## 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.
Rendered output looks like,

Numbered captions on customized and reactive figure in R markdown HTML file

In recent years, it has been possible to add numbering to the figure captions on R chunks in html_document2, as outlined in Yihui Xie's online text for bookdown. However, it has been more difficult to preserve this numbering while also having custom figures output from these chunks. For example, trying to create the custom figures using CSS flexbox from Carson Sievert's online text.
There are several other threads that discuss numbering HTML Rmd figures and using hooks or CSS counters to add custom numbering. However, I could not find a solution that allowed for a custom figure as well as html_document2 numbering to be preserved.
In the example below, I want a side-by-side plotly graphic to be reactive to screen size but also have the same figure caption and numbering.
---
output:
bookdown::html_document2:
self-contained: TRUE
---
```{css, echo=FALSE}
#dualpanel {
width: 50%
}
#media screen and (max-width: 500px) {
#dualpanel {
width: 100%
}}
```
```{r chunk1, echo=FALSE, htmlcap='FIRST FIGURE CAP'}
temp <- plotly::plot_ly(mtcars, x = ~cyl, y=~mpg)
shiny::div(class = 'figure',
style = "display: flex; flex-wrap: wrap; justify-content: center",
shiny::div(temp, id = 'dualpanel'),
shiny::div(temp, id = 'dualpanel'))
```
```{r chunk2, echo=FALSE, fig.cap='SECOND FIGURE CAP'}
plot(mtcars$cyl, mtcars$mpg)
```
This creates an output like this:
In order to address this issue, it is important to know that knitr uses #fig:label in pandoc in order to create the automated numbering in the output. You can see this when you examine the markdown temporary output from the knitr process:
<div class="figure">
<img src="web_tiles_v2_files/figure-html/otherchunk-1.png" alt="SECOND FIGURE CAP" />
<p class="caption">(\#fig:SPECIFICCHUNKOFINTEREST)SECOND FIGURE CAP</p>
</div>
As such, one should be able to maintain the customized figure output by adjusting the custom hook seen in other solutions. This would look like the following, just make sure you have the right chunk label included:
```{r}
knit_hooks$set(customcap= function(before, options, envir) {
if(!before) {
paste('<p class="caption"> (\\#fig:chunk1)',options$customcap,"</p>",sep="")
}
})
```
One could also use some of the internal knitr functions to automatically grab the fig.lp and label: paste('<p class="caption">', knitr:::create_label(options$fig.lp, options$label), options$customcap,"</p>", sep="")
The entire code would look like:
---
output:
bookdown::html_document2:
self-contained: TRUE
---
```{css, echo=FALSE}
#dualpanel {
width: 50%
}
#media screen and (max-width: 500px) {
#dualpanel {
width: 100%
}}
```
```{r}
knit_hooks$set(customcap= function(before, options, envir) {
if(!before) {
paste('<p class="caption"> (\\#fig:chunk1)',options$customcap,"</p>",sep="")
}
})
```
```{r chunk1, echo=FALSE, customcap='FIRST FIGURE CAP'}
temp <- plotly::plot_ly(mtcars, x = ~cyl, y=~mpg)
shiny::div(class = 'figure',
style = "display: flex; flex-wrap: wrap; justify-content: center",
shiny::div(temp, id = 'dualpanel'),
shiny::div(temp, id = 'dualpanel'))
```
```{r chunk2, echo=FALSE, fig.cap='SECOND FIGURE CAP'}
plot(mtcars$cyl, mtcars$mpg)
```
This produces an output that has the dynamic elements and maintains labeling.

Rendering problem cross-reference equation in r markdown HTML

I usually reference equations in rmd using \label{} and \eqref{} combination. (I know \#ref, but this seems only works in bookdown::pdf_document or bookdown::html_document) For example,
---
title: "Untitled"
author: "Blended"
date: '2019 3 14 '
output:
html_document: default
pdf_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(comment = "#>")
```
\begin{equation} \label{eq:test}
Y_i = \beta_0 + \beta_1 x_i + \epsilon_i
\end{equation}
Equation $\eqref{eq:test}$ works in PDF, but does not works in HTML.
This works well in pdf document.
However, when rendering html, it gives (???), not (1):
I think this is related to this issue: Support LaTeX environments in Markdown -> HTML conversion, i.e. MathJax occurs the error.
But I cannot see any solution of this.
Is it possible to use \eqref{eq:} normally in html document?
Add the following script at the beginning of your document body:
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: { equationNumbers: { autoNumber: "AMS" } }
});
</script>
It configures MathJax to automatically number equations. More details here.

show html table (via xtable) in knitr-powered document

I am trying to figure out how to use xtable when creating html pages with knitr.
My main reason to work with xtable is because I want to be able to rotate column names and/or rownames.
This is my .rmd document:
---
output: html_document
---
```{r, echo=FALSE}
library(xtable)
data(tli)
tli.table <- xtable(tli[1:10,])
align(tli.table) <- "|r|r|lp{3cm}l|r|"
tt1 <- print(tli.table, rotate.rownames=TRUE,
rotate.colnames=TRUE, type = "html")
```
```{r, echo=FALSE, results = 'asis'}
tt1
```
When I knit this document to html with knit2html, the row and column names are messed up and the html code is echoed as well. What am I doing wrong? (or is there a better way to construct nicely laid out html tables through knitr?)
Peter,
I am also frustrated with the odd behaviour of xtable when recreating tables that used to work before but not in the new R Markdow v2 using pandoc for the conversion to html.
The most I could do with your table was make it render pretty but no local column alignment or column header rotation. To do this put all the code in one r chunk with the option results='asis'.
This worked for me using RStudio 0.98.1103, R version 3.1.3 (2015-03-09), Platform: x86_64-pc-linux-gnu (64-bit), Running under: Ubuntu precise (12.04.5 LTS), knitr_1.9, rmarkdown_0.5.1, and xtable_1.7-4:
Since you mention using knit2html (not available for R 3.1.3) please try my code in your installation and see if it still works.
If so this might be a reason not to get latest versions just yet.
Using Knitr's Kable the headings appear consistent with the default alignment of right-justified for numeric columns and left-justified otherwise. Xtable's headings appear always to be centred and I can't find the option for changing this behaviour.
---
output:
html_document:
self_contained: false
theme: flatly
keep_md: true
---
<style type="text/css">
table { max-width: 200%;
border: 1px solid #ccc; }
th { background-color: #000000;
color: #ffffff;
width: 2.5cm; }
td { background-color: #dcdcdc }
</style>
```{r, echo=FALSE, results = 'asis'}
library(xtable)
data(tli)
tli.table <- xtable(tli[1:10,])
align(tli.table) <- "|r|r|lp{3cm}l|r|"
print(tli.table,
rotate.rownames=F,
rotate.colnames=F,
type="html",
include.rownames = F)
```
```{r via kable, echo=FALSE, results='markup'}
require(knitr)
kable(tli.table, format = "html",
padding = 0,
row.names=F,
caption = "Via kable")
```

Resources