RMarkdown: knitr::kable::format.args does not work globally - r

I have an R code (RMarkdown) to generate a table with knitr.kable. As I will need to generate several tables with the same formatting, from several data.frames, placed as settings globally. However the format.args option does not work globally.
This way it works:
---
title: "Indicadores Fiscais e Gerenciais da Câmara de Vereadores"
author: "Everton da Rosa"
date: "`r Sys.Date()`"
output:
pdf_document:
toc: yes
toc_depth: 4
fig_caption: yes
number_sections: yes
html_document:
toc: yes
toc_depth: 4
theme: readable
number_sections: yes
df_print: kable
fig_caption: yes
---
```{r setup, include=FALSE}
options(
encoding = 'ISO-8859-1',
knitr.kable.NA = '',
knitr.kable.digits = 2,
knitr.kable.format='latex'
)
knitr_kable_format_args = list(big.mark='.', decimal.mark=',', nsmall=2)
knitr::opts_chunk$set(echo = FALSE)
knitr::opts_chunk$set(result = 'hold')
#if (!require("devtools")) install.packages('devtools')
#library(devtools)
if(!require('tidyverse')) install.packages('tidyverse')
library(tidyverse)
if(!require('stargazer')) install.packages('stargazer')
library(stargazer)
```
```{r}
# Caminho para o arquivo com os dados
ds_file <- 'indicadores cm.xlsx'
```
## Resultado Orçamentário
```{r}
df_ro <- readxl::read_excel(ds_file, sheet='ResultadoOrcamentario')
knitr::kable(df_ro, align=c('l', 'r', 'r'), caption='Resultado Orçamentário', format.args = knitr_kable_format_args)
```
The Output:
However, if I remove format.args from the knitr.kable() call and put it in the option() call, it stops working:
---
title: "Indicadores Fiscais e Gerenciais da Câmara de Vereadores"
author: "Everton da Rosa"
date: "`r Sys.Date()`"
output:
pdf_document:
toc: yes
toc_depth: 4
fig_caption: yes
number_sections: yes
html_document:
toc: yes
toc_depth: 4
theme: readable
number_sections: yes
df_print: kable
fig_caption: yes
---
```{r setup, include=FALSE}
options(
encoding = 'ISO-8859-1',
knitr.kable.NA = '',
knitr.kable.digits = 2,
knitr.kable.format='latex',
knitr.kable.format.args = list(big.mark='.', decimal.mark=',', nsmall=2)
)
knitr::opts_chunk$set(echo = FALSE)
knitr::opts_chunk$set(result = 'hold')
#if (!require("devtools")) install.packages('devtools')
#library(devtools)
if(!require('tidyverse')) install.packages('tidyverse')
library(tidyverse)
if(!require('stargazer')) install.packages('stargazer')
library(stargazer)
```
```{r}
# Caminho para o arquivo com os dados
ds_file <- 'indicadores cm.xlsx'
```
## Resultado Orçamentário
```{r}
df_ro <- readxl::read_excel(ds_file, sheet='ResultadoOrcamentario')
knitr::kable(df_ro, align=c('l', 'r', 'r'), caption='Resultado Orçamentário')
```
Number formatting no longer works:
I looked for help in the documentation and on the internet, but I didn't find anything about it.

I don't see anything in the documentation that suggests putting that value in options() should work. The default for format.args is list(), not getOption("knitr.kable.format.args").
You might want to make a suggestion to Yihui to make that change. In the meantime, you can do it yourself:
kable <- function(..., format.args = getOption("knitr.kable.format.args", list())
knitr::kable(..., format.args = format.args)
After this, call kable() for your version, and knitr::kable() for the original one.

Related

How can I get the order of plots correct in an rmd? [How can I control the print-time of messages?]

As the minimal reproducible example below shows, plot 2 appears too late.
How can I fix this?
It seems, the message screws everthing up. Most likely related: this and this.
---
title: "Run all test-cases"
author: "STCH"
date: "`r Sys.Date()`"
output:
html_document:
keep_md: yes
number_sections: yes
toc: yes
toc_depth: 2
code_folding: hide
pdf_document:
number_sections: yes
toc: yes
toc_depth: '2'
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, fig.width = 10)
testfun <- function() {
message("in testfun")
Sys.sleep(10)
plot(3, main = "testfun 3")
return(0)
}
```
# All test cases `decreasing.benefits = TRUE`
```{r}
for (i in 1){#c(1:7)) {
cat("====================================================================\n")
plot(1, main = "1")
print("After plot 1, before plot 2")
plot(2, main = "2")
print("After plot 2, before plot 3 (Wrong!!??, appears BEFORE plot 2)")
r <- testfun()
}
```
From the docs ?message:
message(..., domain = NULL, appendLF = TRUE)
so it seems you can only control the domain (which has to with translation) and the line ending.

R Position of figures in RMarkdown

I want to knit an article in RMarkdown but the figures (tables) don't appear at the correct position in the document (pdf).
Here I can show you my problem in the example data. The table should appear after the appendix: Can someone show me how I can solve this problem?
And here is y example code:
---
title: "title"
subtitle: "subtitle"
author: "me"
date: "`r format(Sys.time(), '%B %d, %Y')`"
keywords: "keywords"
output:
pdf_document:
fig_cap: yes
keep_tex: yes
documentclass: article
capsize: normalsize
fontsize: 11pt
geometry: margin=1in
spacing: doublespacing
footerdate: yes
abstract: 'Insert abstract here'
---
\newcommand*{\keywords}[1]{\textbf{\textit{Keywords---}} #1}
\keywords{keywords}
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, fig.pos= "h", out.extra = '')
##required packages
library(tidyverse)
library(knitr)
library(kableExtra)
```
# Introduction
# Literature review
# Data and Methodology
# Empirical Results
# Conclusions
\newpage
# References {-}
<div id="refs"></div>
\newpage
# Appendix
```{r echo=F, warning=F, message=F}
df1 <- tibble(column1= 1:10, column2=11:20)
df1%>%kable("latex",
booktabs=T,
caption = "Dataframe 1")%>%
kable_styling()
```
Just add latex_options=c("hold_position") inside kable_stylying:
df1 <- tibble(column1= 1:10, column2=11:20)
df1 %>%
kable("latex", booktabs=T, caption = "Dataframe 1") %>%
kable_styling(latex_options = c("hold_position"))

R Markdown internal link to tables

Is there a possibility to create an internal link to a table in a rmarkdown-article?
I would like to click on this link and then I automatically come to my table.
I want to set the internal link in the text in the Empirical Results-part for table_1.
I've already tried [#table_1] but it doesn't work.
can someone help me?
Here is my example code:
---
title: "title"
subtitle: "subtitle"
author: "me"
date: "`r format(Sys.time(), '%B %d, %Y')`"
keywords: "keywords"
output:
pdf_document:
fig_cap: yes
keep_tex: yes
documentclass: article
capsize: normalsize
fontsize: 11pt
geometry: margin=1in
spacing: doublespacing
footerdate: yes
abstract: 'Insert abstract here'
---
\newcommand*{\keywords}[1]{\textbf{\textit{Keywords---}} #1}
\keywords{keywords}
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
##required packages
library(tidyverse)
library(knitr)
library(kableExtra)
```
# Introduction
# Literature review
# Data and Methodology
# Empirical Results
In table_1 you can see something....
[#table_1]
# Conclusions
\newpage
# References
\newpage
# Appendix
```{r echo=F, warning=F, message=F}
df1 <- tibble(column1= 1:10, column2=11:20)
table_1 <-df1%>%kable("latex",
booktabs=T,
caption = "example table")%>%
kable_styling(latex_options = "hold_position")
table_1
```

How to change the font used inside the chunks when knitting as tuffte_handout pdf?

I am working in a book, using R and the Tufte library.
I am using the following YAML for each .Rmd Chapter:
---
title: "Chapter 2: A First Linear Program"
header-includes:
\usepackage{longtable}
\usepackage{caption}
output:
tufte::tufte_handout:
citation_package: natbib
latex_engine: xelatex
highlight: monochrome
tufte::tufte_html: default
tufte::tufte_book:
citation_package: natbib
latex_engine: xelatex
---
\pagestyle{headings}
```{r setup, include=FALSE}
library(tufte)
library(tint)
library(knitr)
library(gridExtra)
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(tidy = F)
knitr::opts_chunk$set(cache = TRUE)
knitr::opts_chunk$set(width = 30)
```
And the following one is the YAML for the index .Rmd file:
---
title: "Operations Research Using R<br />"
author: "Timothy R. Anderson"
date: "`r Sys.Date()`"
site: bookdown::bookdown_site
documentclass: book
bibliography: ["Master4Bookdowns.bib"]
---
# Preface {-}
I have tried different options like adding the sansfont and mainfont in YAML:
output:
tufte::tufte_handout:
citation_package: natbib
latex_engine: xelatex
highlight: monochrome
sansfont: Calibri Light
mainfont: Calibri Light
But it didn't change the font inside the chunk, only the text outside.
Here a simpler example document showing my attempt to change monofont as suggested in the comments:
---
title: "Chapter 2: A First Linear Program"
header-includes:
\usepackage{longtable}
\usepackage{caption}
output:
tufte::tufte_handout:
citation_package: natbib
latex_engine: xelatex
toc: TRUE
number_sections: true
highlight: monochrome
monofont: Times New Roman
tufte::tufte_html: default
tufte::tufte_book:
citation_package: natbib
latex_engine: xelatex
---
\pagestyle{headings}
```{r setup, include=FALSE}
library(tufte)
library(tint)
library(knitr)
library(gridExtra)
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(tidy = F)
knitr::opts_chunk$set(cache = TRUE)
knitr::opts_chunk$set(width = 30)
```
This is an example, where we can see that text in the book is affected by the use of command
monofont: Times New Roman in the YAML. However, we can see that next chunk, the oucome when generating the tuffte_handout pdf is using a different font and also using multiple colors (no only black as in the main body).
```{r base_case_no_pipes_step_4}
model0d <- c("example", 6 + 2 <= 2000)
#fabrication
model0e <- c("example", 8 + 6 <= 2000)
#assembly
```
You have to bring the YAML headers to the right level:
monofont et al. are top-level headers
highlight is below the output format, not below output
The following example uses "Times New Roman" for the code block and XeLaTeX's default font (Latin Modern) for the main text. You can change that with mainfont. In addition, there is no syntax highlighting:
---
title: "Chapter 2: A First Linear Program"
header-includes:
- \usepackage{longtable}
- \usepackage{caption}
monofont: Times New Roman
output:
tufte::tufte_handout:
citation_package: natbib
latex_engine: xelatex
toc: TRUE
number_sections: true
highlight: monochrome
tufte::tufte_html: default
tufte::tufte_book:
citation_package: natbib
latex_engine: xelatex
---
\pagestyle{headings}
```{r setup, include=FALSE}
library(tufte)
library(tint)
library(knitr)
library(gridExtra)
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(tidy = F)
knitr::opts_chunk$set(cache = TRUE)
knitr::opts_chunk$set(width = 30)
```
This is an example, where we can see that text in the book is affected by the use of command
monofont: Times New Roman in the YAML. However, we can see that next chunk, the oucome when generating the tuffte_handout pdf is using a different font and also using multiple colors (no only black as in the main body).
```{r base_case_no_pipes_step_4}
model0d <- c("example", 6 + 2 <= 2000)
#fabrication
model0e <- c("example", 8 + 6 <= 2000)
#assembly
```
Result:

How can I control fontsize and linestretch of code chunks independently from the main text in bookdown?

Using bookdown to output a .pdf document the YAML within the index.Rmd looks like this currently:
---
title: "My title"
author:
- 'me'
output:
bookdown::pdf_document2:
includes:
in_header: latex/preamble.tex
keep_tex: yes
site: bookdown::bookdown_site
documentclass: book
geometry: "left=3.5cm, right=2.5cm, top=2.5cm, bottom=2.5cm"
fontsize: 12pt
linestretch: 1.5
bibliography: [packages.bib, referencias.bib]
linkcolor: NavyBlue
biblio-style: apalike
link-citations: yes
toc-depth: 2
lof: True
lot: True
---
How can I control fontsize and linestretch of code chunks independently from the main text? This answer provides a solution to control font size, but not line spacing.
It's is the same idea as here but now we just alter the source hook:
```{r setup, include=FALSE}
def.source.hook <- knitr::knit_hooks$get("source")
knitr::knit_hooks$set(source = function(x, options) {
x <- def.source.hook(x, options) # apply default source hook
ifelse(!is.null(options$linestretch), # if linestretch is not NULL, apply linestretch
paste0("\\linespread{", options$linestretch,"}\n", x, "\n\n\\linespread{1}"), # reset linestretch after the chunk!
x)
})
```
Now you can copy and paste the ifelse statement from the other answer into this hook as well and you can control both.
Full example:
---
title: "Linestretch"
date: "20 December 2018"
header-includes:
- \usepackage{lipsum}
output:
bookdown::pdf_document2:
keep_tex: true
linestretch: "`r (lstr <- 1.5)`"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(eval = F)
def.source.hook <- knitr::knit_hooks$get("source")
knitr::knit_hooks$set(source = function(x, options) {
x <- def.source.hook(x, options)
x <- ifelse(!is.null(options$linestretch),
paste0("\\linespread{", options$linestretch,"}\n", x, "\n\n\\linespread{", lstr,"}"),
x)
ifelse(!is.null(options$size),
paste0("\\", options$size,"\n\n", x, "\n\n \\normalsize"),
x)
})
```
## R Markdown
\lipsum[30]
```{r, linestretch = 1, size="Large"}
head(mtcars)
head(mtcars)
```
\lipsum[30]

Resources