I use kableExtra package in rmarkdown (bookdown) to generate nice looking tables in pdf outputs. All works well except for the rendering of LaTeX code in headers. A header named like $\\alpha$ isn't rendered as the Greek alpha. The result is just a $\alpha$ shown in the pdf document.
Additional information: I use format = "latex" and escape = TRUE. If I use escape = FALSE, I get an error when rendering the document:
I was unable to find any missing LaTeX packages from the error log _main.log.
! Misplaced \noalign.
\cmidrule ->\noalign
{\ifnum 0=`}\fi \#ifnextchar [{\#cmidrule }{\#cmidrule ...
l.1293 \cmidrule
{3-7}
I am sorry for not giving a reproducible example. I somehow hope it is a setting I missed somewhere in the kableExtra. If it is needed I will make an example though.
Many thanks in advance!
You could try this:
---
title: "Use slashes to escape"
author: "bttomio"
date: "3/24/2021"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r echo=F}
library(kableExtra)
x <- matrix(1:4, ncol=2)
kbl(x, col.names=c('$\\alpha$', 'B'), align = 'c', 'latex', booktabs = T, escape = F) %>%
add_header_above(c("$\\\\alpha$" = 2), escape = F)
```
-output
Related
I have some R code in a package. I don't want to copy that code, but I want to display it in a pretty way in Word with syntax highlighting without any manual steps.
I looked at styler::style_text in combination of capture.output and that looks nice in the browser, but all the formatting is lost when knitting to Word. Is there some way to preserve it? I'm thinking the best thing would be to have Word native styling but the next best (acceptable) thing would be to somehow render the output to an image and include that. Has anyone done these things to document their code in a report?
show_code = function (fun) {
stopifnot(is.function(fun))
out = capture.output(fun)
n = length(out)
without_bytecode_and_env_lines = -1*c(n-1, n)
code = paste(out[without_bytecode_and_env_lines], collapse = "\n")
styler::style_text(code)
}
I believe you are trying to use syntax highlighting on the output of show_code and to do that, you simply need to use the options comment="" and class.output="r" and syntax highlighting will apply to the output.
---
title: "Source Code highlighting"
output:
word_document:
highlight: kate
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
```{r echo=FALSE}
show_code = function (fun) {
stopifnot(is.function(fun))
out = capture.output(fun)
n = length(out)
without_bytecode_and_env_lines = c(n-1, n)
code = paste0(out[-without_bytecode_and_env_lines], collapse = "\n")
styler::style_text(code)
}
```
### The source code for `lm`
```{r comment='', echo=FALSE, class.output = "r"}
show_code(lm)
```
kableExtra seems to disrupt the proper formatting of kables in LaTeX when the caption contains certain characters.
kableExtra::kable will be formatted properly if no caption is used, or if standard knitr::kable is used.
The following code will yield oddly formatted results if kableExtra is loaded.
---
title: "Mock"
output:
pdf_document:
keep_tex: true
---
```{r header, echo= FALSE, include = FALSE, warning= FALSE}
library(skimr)
library(knitr)
# library(kableExtra)
resumir <- function(var, unit = "", caption = NULL) {
if(is.null(caption)) {caption <- deparse(substitute(var))}
skim_to_wide(var) %>%
mutate_all(as.numeric) %>%
kable(caption = paste0(caption, " (", unit, ")"))
}
mtcars2 <- mtcars %>%
rename("NO_CYL" = 'cyl', "PEAK_PERF" = "mpg")
attach(mtcars2)
```
`r resumir(POWER_HRS, unit = "$hours$")`
I think I know already what's happening but after all the hassle I went through to find the issue I think it's good if this goes up on SO and someone posts an answer (or I will after a bit).
So, to keep it simple, the problem turned out to be having underscores in the caption. The only solution that has worked is to remove them, which is not overly unreasonable.
---
title: "Mock"
output:
pdf_document:
keep_tex: true
---
```{r header, echo= FALSE, include = FALSE, warning= FALSE}
library(knitr)
library(kableExtra)
attach(mtcars)
```
`r kable(cyl, caption = "Cylinder_No.")`
There was a bug report for knitr but knitr currently works fine.
I have an R Markdown table with this \rule{1cm}{0.4pt} LaTeX command in each cell of one column. The table formats just fine with kable if I do not include the kableExtra package. If I do include kabelExtra, the LaTeX command is no longer interpreted. The results are shown below, without and with kableExtra. No other change was made. The top example is my desired result.
I inspected the .tex output. kableExtra seems to format the LaTeX command as literal text: \textbackslash{}rule\{1cm\}\{0.4pt\} instead of the command shown above.
I want to use kableExtra for other features like setting column widths but I need it to interpret the LaTeX commands. I did not find anything in the manual or vignettes that seemed to address included LateX commands. Am I missing something?
Edit
I tried adding format = "latex" to the kable call when using kableExtra but undesired result remained.
MWE
---
title: "Without kableExtra"
output:
pdf_document:
keep_tex: TRUE
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
library(tibble)
library(knitr)
#library(kableExtra)
a = seq(1:3)
b = seq(4:6)
tab <- as.tibble(cbind(a,b))
tab <- add_column(tab, c = "\\rule{1cm}{0.4pt}")
```
```{r}
kable(tab,
booktabs = TRUE,
longtable = TRUE)
```
Results
When using kableExtra you should add the argument escape = FALSE to your kable() call. The escape argument let you use LaTeX commands in table.
The following works:
---
title: "Without kableExtra"
output:
pdf_document:
keep_tex: TRUE
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
library(tibble)
library(knitr)
library(kableExtra)
a = seq(1:3)
b = seq(4:6)
tab <- as.tibble(cbind(a,b))
tab <- add_column(tab, c = "\\rule{1cm}{0.4pt}")
```
```{r}
kable(tab,
booktabs = TRUE,
longtable = TRUE,
escape = FALSE)
```
Is there a way to prevent group headers from being rendered as bold when using group_rows function in kableExtra?
I have been using the amazing kableExtra package developed by #Hao to decorate tables outputted from knitr::kable. I want to add group headers, but I do not want these to be in bold. These headers are wrapped in \textbf{} when outputted to latex, and I have not been able to work out which kableExtra function does this "code decoration".
Reproducible example:
---
title: "group_rows kableExtra"
output: pdf_document
---
```{r setup, include=FALSE}
require(kableExtra)
require(knitr)
```
```{r table, results='asis'}
knitr::kable(head(mtcars), booktabs = TRUE, format = "latex") %>%
group_rows("Group 1", 2, 3)
```
#bsalzer on github is helping me recently add some customizable options to group_rows including this feature you are asking for. If you install from github, you can do things like
knitr::kable(head(mtcars), booktabs = TRUE, format = "latex") %>%
group_rows("Group 1", 2, 3, bold = F)
and that will do the trick.
I have read a bunch of different posts on justifying xtable tables left but I cannot find details/work out how to make the caption justify left as well. Below is a reproducible example which justifies the table left but leaves the caption centred.
\documentclass{article}
\begin{document}
<<echo = F, results = "asis">>=
df = data.frame(x = c(1,2), y = c(4,6))
library(xtable)
print(xtable(df,digits=0, caption="Caption Left?"), include.colnames=TRUE, size = "small", comment=FALSE, latex.environments="flushleft")
#
\end{document}
I have found out how to do this. Simply import the LaTex Caption package and use the caption setup argument:
\captionsetup{justification = raggedright, singlelinecheck = false}
This will justify the caption to the left. The caption can be returned to its default centred position for additional tables or figures by repeating the function with the following modification before additional tables/figures.
\captionsetup{justification = centering, singlelinecheck = false}
The answered solution is:
\documentclass{article}
\usepackage{caption}
\begin{document}
\captionsetup{justification = raggedright, singlelinecheck = false}
<<echo = F, results = "asis">>=
df = data.frame(x = c(1,2), y = c(4,6))
library(xtable)
print(xtable(df,digits=0, caption="Caption Left?"),include.colnames=TRUE, size = "small", comment=FALSE, latex.environments="flushleft")
#
\end{document}
Which returns:
This operation is critical for anyone wishing to produce Markdown files in APA format since table captions are typically left-justified.
I'm going to clarify Robin's answer a little bit because, because totally new to the Markdown/Latex interface, it took me some time to figure out.
Upload the "caption" package (documentation available here) by including the
\usepackage{caption}
command in YAML (header) part of the document, preceded by
header-includes:
So an an entire YAML section at the header of the document might look like this:
---
title: "Supplementary Materials"
author: ""
date: "3/30/2018"
output:
pdf_document: default
editor_options:
chunk_output_type: inline
header-includes:
- \usepackage{caption}
---
Then, at any point in the document, before a code chunk (in its own white space), you can insert the code:
\captionsetup{justification = raggedright, singlelinecheck = false}
To change the settings back again, you can re-insert this code at any point in white space of the Markdown file (not in a code chunk!)
E.g.
\captionsetup{justification = centering, singlelinecheck = false}
If you don't mind using an alternative package (my own):
library(huxtable)
ht <- as_huxtable(df)
caption_pos(ht) <- "bottomleft"
print_latex(ht) # or just do `ht` if within a knitr or Rmd document