How can I put 2 chunks of code side by side in the output file of RMarkdown or Quarto ?
Code
library(dplyr)
mtcars %>% select(gear)
library(dplyr)
select(mtcars, gear)
Desired layout in the PDF or HTML file
CodePudding user response:
---
title: "Untitled"
output: html_document
---
:::::::::::::: {.columns}
::: {.column width="50%"}
```{r warning=FALSE,message=FALSE}
library(dplyr)
mtcars %>% select(gear)
```
:::
::: {.column width="50%"}
```{r warning=FALSE,message=FALSE}
library(dplyr)
select(mtcars, gear)
```
:::
::::::::::::::
used This SO question as a resource. This is using pandoc to format the document in Rmarkdown HTML output
CodePudding user response:
The canonical way for something like this is to use column
divs:
::::: columns
::: column
```r
library(dplyr)
mtcars %>% select(gear)
```
:::
::: column
```r
library(dplyr)
select(mtcars, gear)
```
:::
:::::
This will work with HTML, reveal.js, Beamer, and Powerpoint. The default result looks a bit ugly in HTML, as there is no space between the two blocks, but we can fix that with a tiny bit of CSS. We can put it directly into the document:
<style>
.column { padding-right: 1ex }
.column .column { padding-left: 1ex }
</style>
Things get more complicated if we wish to do the same for PDF. We'll need convert the divs into a table, as that's the most effective way to get elements side-by-side. But that requires some heavier tools. In the YAML header, add
output:
pdf_document:
pandoc_args:
- "--lua-filter=columns-to-table.lua"
Then save the below code into a file column-to-table.lua
.
function Div (div)
if div.classes:includes 'columns' then
local columns = div.content
:filter(function (x)
return x.classes and x.classes[1] == 'column'
end)
:map(function (x)
return x.content
end)
local aligns = {}
local widths = {}
local headers = {}
for i, k in ipairs(columns) do
aligns[i] = 'AlignDefault'
widths[i] = 0.98/ #columns
end
return pandoc.utils.from_simple_table(
pandoc.SimpleTable('', aligns, widths, headers, {columns})
)
end
end
You can get rid of the lines around the table by adding
\renewcommand\toprule[2]\relax
\renewcommand\bottomrule[2]\relax
at the beginning of your document.