Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to adjust code block line spacing in knitr?

Tags:

r

rstudio

knitr

When you use knitr to render r-markdown files into either HTML or pdf, the code chunks in the output document have what to me looks like excessive line spacing. When I want to output the results of summary() this turns what is normally a concise output into something way too long.

Here's a comparison:

Comparison of console and knitr line spacing

I've looked and looked and I cannot find a way to adjust knitr's line spacing.

Of course I could use xtable to format the summary() output, but it only wants to output the "tabular" part of the output and doesn't include the R^2 etc. in it.

Is there a way to adjust knitr's line spacing so it is more compact?

like image 872
ccoffman Avatar asked Jul 02 '14 17:07

ccoffman


People also ask

How do I add a space in R markdown?

To create vertical space (Markdown to PDF), I use   This command works like \vspace{12pt} for latex. Fantastic!

How do I insert a code block in R?

You can insert an R code chunk either using the RStudio toolbar (the Insert button) or the keyboard shortcut Ctrl + Alt + I ( Cmd + Option + I on macOS).

How does R knitr work?

When you run render , R Markdown feeds the . Rmd file to knitr, which executes all of the code chunks and creates a new markdown (. md) document which includes the code and its output. The markdown file generated by knitr is then processed by pandoc which is responsible for creating the finished format.


1 Answers

You can do this for HTML output. Create your own style.css file in the same directory as your document, and decrease the line spacing there:

div pre {
  line-height: normal;
}

Then reference that CSS file in your YAML front matter:

---
...
output:
  html_document:
    css: style.css
---

I'm not sure how to do it for PDF. Note that most LaTeX commands in your document will be passed directly through pandoc to the layout engine, so if you can find a solution using raw LaTeX it may be possible to inject it directly into your R Markdown document.

like image 98
Jonathan Avatar answered Oct 17 '22 13:10

Jonathan