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.
Related
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'))
))
```
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.
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)
The following code produces 2 tables on top of each other. How would I set it to have them aligned side by side, e.g. 3 to a row?
---
title: "sample"
output: pdf_document
---
```{r global_options, R.options=knitr::opts_chunk$set(warning=FALSE, message=FALSE)}
```
```{r sample, echo=FALSE, results='asis'}
library(knitr)
t1 <- head(mtcars)[1:3]
t2 <- head(mtcars)[4:6]
print(kable(t1))
print(kable(t2))
```
Output looks like this:
Just put two data frames in a list, e.g.
t1 <- head(mtcars)[1:3]
t2 <- head(mtcars)[4:6]
knitr::kable(list(t1, t2))
Note this requires knitr >= 1.13.
I used this Align two data.frames next to each other with knitr? which shows how to do it in html and this https://tex.stackexchange.com/questions/2832/how-can-i-have-two-tables-side-by-side to align 2 Latex tables next to each other. It seems that you cannot freely adjust the lines of the table as you can do it with xtable (does anybody know more about this?). With format = Latex you get a horizontal line after each row. But the documentation shows two examples for other formats. One using the longtable package (additional argument: longtable = TRUE) and the other using the booktabs package (booktabs = TRUE).
---
title: "sample"
output: pdf_document
header-includes:
- \usepackage{booktabs}
---
```{r global_options, R.options=knitr::opts_chunk$set(warning=FALSE, message=FALSE)}
```
```{r sample, echo=FALSE, results='asis'}
library(knitr)
library(xtable)
t1 <- kable(head(mtcars)[1:3], format = "latex", booktabs = TRUE)
t2 <- kable(head(mtcars)[4:6], format = "latex", booktabs = TRUE)
cat(c("\\begin{table}[!htb]
\\begin{minipage}{.5\\linewidth}
\\caption{}
\\centering",
t1,
"\\end{minipage}%
\\begin{minipage}{.5\\linewidth}
\\centering
\\caption{}",
t2,
"\\end{minipage}
\\end{table}"
))
```
here a solution for html documents
(As this question was asked very broadly and not specifically referring to LaTeX).
Requires knitr and kableExtra
---
title: "Side by side"
output: html_document
---
```{r sample, echo=FALSE}
library(knitr)
library(kableExtra)
t1 <- head(mtcars)[1:3]
t2 <- head(mtcars)[4:6]
```
## as list
```{r}
kable(list(t1, t2))
```
## with float
```{r, echo = FALSE}
kable(t1) %>%
kable_styling(full_width = FALSE, position = "float_left")
kable(t2) %>%
kable_styling(full_width = FALSE, position = "left")
```
It is intentional that table t2 gets position = "left". If you allow it to float, this will not block the rest of the paragraph and mess up the following lines in your document.
result:
In Quarto, you can use layout-ncol. This works both for HTML and PDF outputs.
---
title: "sidebyside"
format: pdf
editor: visual
---
```{r}
#| layout-ncol: 2
#| tbl-cap: "Tables"
#| tbl-subcap: ["A table", "Another table"]
library(knitr)
# table on the left
kable(head(mtcars))
# table on the right
kable(head(cars))
```
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