How to change code output background colour when knitting rmarkdown to pdf? - r

I'm preparing a pdf document with rmarkdown. I'd like to know whether there is a way to change the code output's background color, so that the output is more distinguishable from other texts.
My current solution only changes the color of the code chunk itself. Thanks!
---
title: "Untitled"
output:
pdf_document:
highlight: default
header-includes: \usepackage{xcolor}
---
\definecolor{shadecolor}{RGB}{225, 225, 225}
Plain text.
```{r}
a <- c(1,2,3,4,5)
b <- c(1,2,3,4,5)
df <- data.frame(a, b)
# take a look at our data frame
df
```
Plain text.

A nice trick is to pass a class name to class.output, and then shadecolor will also be applied on chunk output too.
I have used "shadebox" as a class name but it can be any valid string.
---
title: "Untitled"
output:
pdf_document:
highlight: default
header-includes: \usepackage{xcolor}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, class.output="shadebox")
```
\definecolor{shadecolor}{RGB}{225, 225, 225}
Plain text.
```{r}
a <- c(1,2,3,4,5)
b <- c(1,2,3,4,5)
df <- data.frame(a, b)
# take a look at our data frame
df
```
Plain text

Related

How to utilise data from another package as parameter in rmarkdown

For my rmarkdown I wish to be able to parameterise data from the palmerpenguins package. However I am unable to utilise it when I specify it as a parameter and go to knit my file. params$data only prints out the word penguins when I want it to print out the whole data table, and params$data$species fails. Attached below is also the error code produced. Any clue what I'm doing wrong?
---
title: "Project_Report"
author: "Caitlin Luo"
date: "`r Sys.Date()`"
output: pdf_document
params:
data: !r penguins
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(palmerspenguins)
```
```{r penguins}
params$data
params$data$species
```
If the data is from another package you have to use the package::function notation in the YAML.
e.g.
---
title: "Project_Report"
author: "Caitlin Luo"
date: "`r Sys.Date()`"
output: pdf_document
params:
data: !r palmerpenguins::penguins
---

Cross-referencing in R bookdown makes the figure name incorrect

I am producing plotly charts in Rmarkdown and give them name and caption. but as soon as I cross reference them in the document, their name is ruined.
Here is the code:
---
title: "Preliminary Statistics"
author: "Babak"
date: "6/28/2021"
output:
bookdown::html_document2:
fig_caption: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = FALSE,
fig.width=9,
fig.height=5 ,
message=FALSE,
warning=FALSE)
```
```{r Area_duplicate, fig.cap = "Area of duplicated and unique properties by municipality"}
<PLOT CODES>
```
Plot \#ref(fig:Area_duplicate) shows the area od duplicated properties in the dataset grouped by municipality.
result:
screenshot of the caption
What should I do to resolve this issue?
Replace the underscore in the name with a "-".

Insert list of figures / tables using the captioner package (R)

I use the package captioner to automatically reference tables, figures, supplementary data, codes, etc in my normal work. Althoug I can use it efficiently, I would like to create a section in the RMarkdown document which contains the list (index) of all the elements of the same style.
Let's say I have 2 tables in a RMarkdown document.
---
title: "Untitled"
author: "Mario Modesto Mata"
date: "6/7/2020"
output:
pdf_document: default
html_document: default
---
```{r setup, include=FALSE}
library(captioner)
table_number <- captioner(prefix = "Table")
```
The data frame of mtcars is in `r table_number("table1", display="cite")`.
```{r}
data(mtcars)
print(mtcars)
```
`r table_number(name = "table1", caption = "Caption of table1 (mtcars)")`
The data frame of mtcars is in `r table_number("table2", display="cite")`.
```{r}
data(iris)
print(iris)
```
`r table_number(name = "table2", caption = "Caption of table2 (iris)")`
I would like to include at the beginning an index of the tables that were defined with the function table_number().
Is there a way to do this? I would prepare later the equivalent index for figures and other topics...

Looping Flextables in R Markdown documents with Word output

I am looking to print multiple flextables in a single R Markdown document. This is not challenging when using html output, but I need Word output.
With html output, the following R Markdown code (example taken from https://davidgohel.github.io/flextable/articles/offcran/examples.html#looping-in-r-mardown-documents) produces a document with multiple Flextables:
---
output:
html_document: default
---
```{r}
library(htmltools)
library(flextable)
ft <- flextable(head(iris))
tab_list <- list()
for(i in 1:3){
tab_list[[i]] <- tagList(
tags$h6(paste0("iteration ", i)),
htmltools_value(ft)
)
}
tagList(tab_list)
```
I have been unable to get an equivalent output using Word document output.
The solution proposed in
How to knit_print flextable with loop in a rmd file similarly works fine with html output, but I have failed to get this to render correctly with Word output.
Any advice on a R Markdown Word document output equivalent of the above example would be very helpful!
You need to use flextable::docx_value and the chunk option results='asis'
---
title: "Untitled"
output: word_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(flextable)
```
```{r results='asis'}
ft <- flextable(head(iris))
for(i in 1:3){
cat("<w:p/>")## add this to add an empty new paragraph between tables
flextable::docx_value(ft)
}
```

Is there a way to add latex specification in 'column_spec' function in R kable?

I am trying to modify the appearance of a table using kable and kableExtra packages in R Markdown knitting to PDF output.
In particular, I would like to remove all borders from the table and add only one horizontal line under the header and one vertical line next to the row names.
At the moment, I have this code:
---
header-includes: \setmainfont[Path = C:/Windows/Fonts/]{Arial}
\usepackage{colortbl}
\arrayrulecolor{white}
output:
pdf_document:
latex_engine: xelatex
word_document: default
---
```{r echo=FALSE, message=FALSE, warning=F, paged.print=TRUE}
library(kableExtra)
library(magrittr)
DATA<- data.frame(jen=c(1,2,3,4,5), feb=c(2,3,4,5,3), mar=c(0,2,4,1,2))
rownames(DATA)<-c("first","second","third","fourth","fifth")
kable(DATA, "latex")
```
Which generates this table:
Table
To delete all borders, I set default borders to be white as the answer to this question suggested.
Now, I would like to add an horizontal blue line under the header and a vertical blue line at the right side of the row names.
I can manage to get the horizontal line with the following:
---
header-includes: \setmainfont[Path = C:/Windows/Fonts/]{Arial}
\usepackage{colortbl}
\arrayrulecolor{white}
output:
pdf_document:
latex_engine: xelatex
---
```{r echo=FALSE, message=FALSE, warning=F, paged.print=TRUE}
library(kableExtra)
library(magrittr)
DATA<- data.frame(jen=c(1,2,3,4,5), feb=c(2,3,4,5,3), mar=c(0,2,4,1,2))
rownames(DATA)<-c("first","second","third","fourth","fifth")
kable(DATA, "latex") %>%
row_spec(0, extra_latex_after = "\\arrayrulecolor[rgb]{0,.275,.725}") %>%
row_spec(1:nrow(DATA), extra_latex_after = "\\arrayrulecolor{white}")
```
Obtaining this.
I would like to do the same with a vertical line but there is no such command as 'extra_latex_after' in the function 'column_spec'. It only accepts 'extra_css' commands which obviously do not work for a PDF output.
My goal is to get something like this.
I know I can get the same result with other packages for tables, but I am wondering if it is possible to get something like this using kable.
Does anyone know if there is a solution for this?
This is indeed not supported so far. You could make a feature request on github.
You can hack this using a regular expression to replace the alignment options in your tabular:
---
title: "Test"
date: 2019-02-13
output: pdf_document
---
```{r header, echo= FALSE, include = T, warning=F}
library(knitr)
tbl <- kable(mtcars[1:4, 1:3], format = "latex")
# here we search for the begin command and its options and replace them
gsub(pattern = "(begin\\{tabular\\})(\\{.*?\\})",
repl = "\\1{l|r !{\\\\color{red}\\\\vrule width 1pt} r|r|}",
x = tbl)
```

Resources