Align xtable caption left in knitr - r

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

Related

How t o enter properly instructions to widen margins a page for RMarkdown pdf.doc

Since I'm facing with an incorrected reporting into pages in RMarkdown, as you could see here:
I was suggested to enter these commands around the line that is supposed to print the table.
<span style='font-size: 0.8em'>
```{r model, echo = FALSE, results = 'asis'}
iwalk(tables_models, ~ cat(knitr::knit_print(.x)))
```
</span>
Since I've tried to reproce that into my doc as follows
Producing red marks and the only way I found to make them set correctly is this:
that does not make the problem fixed, I would like to ask help to set these instructions properly. Thanks
If you want to make a special margin in your file (knitting to pdf), then try this LaTeX-solution:
Add this package to the header:
header-includes:
\usepackage{geometry}
Make a special margin for some pages (you also can use mm, cm):
\newgeometry{top=1in,left=1in,bottom=1in,right=1in}
And after return to your previous style:
\restoregeometry
An example to you:
---
title: "R"
header-includes:
- \usepackage{geometry}
output:
pdf_document: default
---
\newgeometry{top=1in,left=5in,bottom=1in,right=1in}
```{r}
options(width = 100)
matrix(runif(100), ncol = 20)
```
\restoregeometry
\newpage
\newgeometry{top=1in,left=0in,bottom=1in,right=1in}
```{r}
options(width = 100)
matrix(runif(100), ncol = 20)
```
\restoregeometry
\newpage
\newgeometry{top=5in,left=1in,bottom=1in,right=1in}
```{r}
options(width = 100)
matrix(runif(100), ncol = 20)
```
\restoregeometry

How to let bookdown render LaTeX in kableExtra table headers properly?

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

Is there a way to add a scroll bar to dfSummary output in R markdown file?

I've already tried using the print function:
print(dfSummary(df), method = "render")
And also all the solutions here but they don't seem to work with html_document as the output file type of the R Markdown.
Olá, Inês
The answer is in provided link. You just need to add max.tbl.height argument and specify height in pixels:
print(dfSummary(df),
max.tbl.height = 250,
method = "render")
Here goes an reproducible example (see # comments for tips & tricks):
---
title: "Title"
author: "Author"
date: "26/05/2020"
output:
html_document:
toc: TRUE
toc_float: TRUE
---
```{r setup, include = FALSE}
library(knitr)
library(summarytools)
knitr::opts_chunk$set(results = "asis")
```
### Adding a scrollbar to dfSummary
```{r summarytools-css, echo = FALSE}
# with summarytools’ CSS we can cancel Bootstrap’s CSS (both are included by default)
# without it odd layout are expected, especially with dfSummary()
st_css(bootstrap = FALSE)
```
```{r dfSummary, echo = FALSE}
print(dfSummary(tobacco,
style = "grid", # set style to “grid”
valid.col = FALSE, # drop Valid column if redundant
graph.magnif = 0.82), # zoom factor (max = 1) for bar plots and histograms
headings = FALSE,
footnote = NA,
# use maximum table (specified) height (in pixels) and wrap the results in a scrollable window
max.tbl.height = 300,
method = "render")
```
If you have interest, check out Dominic's vignette - "Recommendations for Using summarytools With Rmarkdown".
May I suggest using the package "DT", if you absolutely need dfSummary I can try again, but would need the minimal amount of code for replicate your example. DT has search functionality along with letting the user control how many rows they see when viewing the data.
---
title: "DF summary"
author: "stackoverflow"
date: "5/24/2020"
output: html_document
---
```{r}
library(DT)
datatable(head(mtcars, 30), options = list(
order = list(list(2, 'asc'), list(4, 'desc'))
))
```

Referencing a table in R markdown with knitr

It's possible to reference a figure in knitr like that:
```{r myfig}
plot(1,1)
```
Figure \ref{fig:myfig} shows ...
The same is not possible for tables, e.g.
```{r my_table, results='markup', fig.cap='capture'}
tab <- read.table('my_table.txt', sep = '\t')
kable(tab,
format='pandoc',
digits = 3,
caption =
"Description")
```
Table \ref{table:my_table} shows ...
doesn't work! Is it possible to make this work without digging into latex? If no, what would I have to do to make it work?
With format='pandoc' you need to enter the \label command in the caption.
With format='latex' the reference is automatically created as tab:chunk_label. For example,
---
output:
pdf_document
tables: true
---
```{r results='markup'}
tab <- head(iris)
knitr::kable(tab,
format='pandoc',
digits = 3,
caption = "Pandoc table\\label{tab:pandoc_table}"
)
```
```{r latex_table, results='markup'}
tab <- head(iris)
knitr::kable(tab,
format='latex',
digits = 3,
caption = "LaTeX table",
booktabs = TRUE
)
```
Table \ref{tab:pandoc_table} was done using Pandoc,
while Table \ref{tab:latex_table} used \LaTeX.
Replace table with tab \#ref(tab:my_table)

Rmarkdown table pushed to two pages when it can fit in one

I'm trying to create separate Rmd files for different tables where each table gets rendered to separate pdfs. Because of some complex formatting issues, I'm using xtable to try and pull this off. I have some tables that I anticipate will fill up a full 8.5x11.0 page with 1 inch margins. But when I render them the first page of the pdf is blank and the second page has the entire, properly formatted table. I'm looking for help to get this to work right. Here's my minimal workable example...
---
output: pdf_document
tables: true
geometry: margin=1.0in
---
```{r results='asis', echo=FALSE, warning=FALSE, eval=TRUE}
require(xtable)
# set up data frame
df <- data.frame(Label=c(letters[1:26], letters[1:13]), Numbers=1:39)
strCaption <- "\\textbf{Supplementary Table 1. This table is just produced with some random data and does not mean anything.}"
# set up xtable output
print(xtable(df, caption = strCaption, label = ""),
size = "normalsize",
include.rownames = FALSE,
include.colnames = TRUE,
caption.placement = "top",
comment=FALSE
)
```
This gets saved as test.Rd and I render using...
library(rmarkdown)
render("test.Rmd"
If I change the margin sizes, it seems to only affect the left and right margin. If I shrink the size of the font, it will fit on one page, but I'd like to keep the font size as is and get rid of the blank first page. Ideas? I'm a bit of a latex newbie so apologies for missing something obvious.
I think if you add the floating = FALSE argument, it should solve the problem. I think this is the LaTex equivalent of the !h here argument when you define the table. I also separated the library call from the other code (and used library instead of require), but that's stylistic and picky.
---
output: pdf_document
tables: true
geometry: margin=1.0in
---
```{r echo=FALSE, warning=FALSE, eval=TRUE, results='hide'}
library(xtable)
```
```{r eval=TRUE, echo=FALSE, results='asis'}
# set up data frame
df <- data.frame(Label=c(letters[1:26], letters[1:13]), Numbers=1:39)
strCaption <- "\\textbf{Supplementary Table 1. This table is just produced with some random data and does not mean anything.}"
# set up xtable output
print(xtable(df, caption = strCaption, label = ""),
include.rownames = FALSE,
include.colnames = TRUE,
caption.placement = "top",
comment=FALSE,
floating=FALSE
)
```
Thanks to the posting from ted-dallas, I was able to figure out that the table.placement option did what I want without having to turn off the floating...
---
output: pdf_document
tables: true
geometry: margin=1.0in
---
```{r results='asis', echo=FALSE, warning=FALSE, eval=TRUE}
require(xtable)
# set up data frame
df <- data.frame(Label=c(letters[1:26], letters[1:13]), Numbers=1:39)
strCaption <- "\\textbf{Supplementary Table 1. This table is just produced with some random data and does not mean anything.}"
# set up xtable output
print(xtable(df, caption = strCaption, label = ""),
size = "normalsize",
include.rownames = FALSE,
include.colnames = TRUE,
caption.placement = "top",
comment=FALSE,
table.placement = "!ht"
)
```
This generates the output I was looking for.

Resources