[rmarkdown]How to deal with table in beamer_presentation - r

When I embed a table generated by using knitr::kable,
I want to adjust the width of the table in beamer_presentation's slide.
Like this picture, some columns don't show in slide when executing the following codes.
Could you tell me how to solve this problem without changing column's names?
---
title: "test"
author: "test"
date: "`r Sys.time()`"
output:
beamer_presentation:
latex_engine: xelatex
fontsize: 6pt
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
knitr::opts_chunk$set(warning = FALSE)
knitr::opts_chunk$set(include = FALSE)
library(tidyverse)
library(kableExtra)
library(knitr)
```
## Table
```{r test, results = "asis",include=TRUE}
test_tbl = tibble(
example_name1 = c("a", "b"),
example_name2 = c("aa", "bb"),
example_name3 = c("aaa", "bbb"),
example_name4 = c("aaaa", "bbbb"),
example_name5 = c("aaaaa", "bbbbb")
)
knitr::kable(test_tbl, format = "markdown")
```

The table is too large to fit on one slide. By adjusting the font size with kableExtra the size of the table can be changed. To do this, set the argument format = "latex" in kable() and then pipe kable_styling().
knitr::kable(test_tbl, format = "latex") %>%
kableExtra::kable_styling(font_size = 7)
It is useful to include LaTeX packages like booktabs to format tables nicely with kable or kableExtra. This is not as flexible as working with LaTeX directly but often leads to quite good results.
First of all, include booktabs in the YAML header.
---
title: "test"
author: "test"
date: "`r Sys.time()`"
header-includes:
- \usepackage{booktabs}
output: beamer_presentation
---
Then set booktabs = TRUE in kable().
knitr::kable(test_tbl, format = "latex", booktabs = T) %>%
kableExtra::kable_styling(font_size = 7)

Related

R Markdown adding page break before plot [duplicate]

I am using bookdown to create pdf reports, but my tables are all floating down to the bottom of the page, regardless of how much space there is. See this example:
---
title: "test_doc"
author: "Jake Thompson"
date: "6/30/2017"
output:
bookdown::pdf_document2:
toc: false
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, collapse = TRUE)
library(tidyverse)
```
# Test heading
Let make a data frame and print it in Table \#ref(tab:test-table)
```{r test-table}
data_frame(col_a = seq_len(5), col_b = rnorm(5), col_c = runif(5)) %>%
knitr::kable(caption = "This is a test")
```
The resulting pdf looks like this:
Why does the table go to the bottom of the page? And is there a way to prevent this behavior?
You can solve this problem with kableExtra by
data_frame(col_a = seq_len(5), col_b = rnorm(5), col_c = runif(5)) %>%
knitr::kable(caption = "This is a test") %>%
kableExtra::kable_styling(latex_options = "hold_position")
It basically insert a [!h] to the LaTeX table environment which will prevent the floating behavior and pin the table at current location.
I had to use
kable_styling(latex_options = "HOLD_position")
Note the uppercase HOLD_position, different from hold_position. See also here.
To be able to use that, I also had to add to the top section of the doc (from How to build a latex kable through bookdown::render_book?):
output:
pdf_document:
extra_dependencies: ["float"]

Rotate table pdf output from Markdown

I want to rotate table output by 90 degrees on pdf. I am using markdown to generate a report and kable to display the tables in a loop. If possible, I would like to continue using kable since there are lot of other things which are dependent on it that I haven't included in this MWE.
This is a simple example using iris dataset. I tried using landscape function from this post Rotate a table from R markdown in pdf
---
output: pdf_document
header-includes:
\usepackage{lscape}
\usepackage{pdfpages}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
Report page -
```{r results='asis'}
library(knitr)
library(kableExtra)
for (i in 1:3) {
print(landscape(kable_styling(
kable(iris[i:(i+5), ], format = "latex", align = "c", booktabs = TRUE,
longtable = TRUE, row.names = FALSE), latex_options = c("striped"), full_width = T)))
}
```
But this only rotates the page number keeping the table as it is.
I am actually looking for a solution which provides me the output in this way -
To clarify, all the pages with table data in it (3 for this example) should be rotated whereas rest of them should remain as it is. Also, I need longtable = TRUE in kable since in my actual example I am printing lot of rows.
Use package rotating
I added a simple example for you.
---
title: "test"
header-includes: \usepackage[figuresright]{rotating}
#or \usepackage[figuresleft]{rotating}
output:
pdf_document:
latex_engine: xelatex
---
```{r setup, include = FALSE}
library(flextable)
ft <- flextable(head(mtcars))
```
\begin{sidewaysfigure}
`r ft`
\end{sidewaysfigure}
```
Further you can modify it for your tasks ;)
I found another way using rotatebox.
---
output: pdf_document
header-includes:
\usepackage{lscape}
\usepackage{pdfpages}
\usepackage{graphicx}
\usepackage[figuresright]{rotating}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
Report page -
```{r results='asis', warning=FALSE, message=FALSE}
library(knitr)
library(kableExtra)
for (i in 1:3) {
cat('\\rotatebox{90}{')
print(kable(iris[i:(i+5), ], format = "latex", align = "c", booktabs = TRUE,
row.names = FALSE))
cat('}')
cat("\n\\newpage\n")
}
```

how to cross reference tables and plots in rmarkdown?

I am using the following template
---
title: "Nice try buddy"
author: "SpaceMan"
date: "13 December 2057"
output:
bookdown::pdf_document2
header-includes:
- \usepackage{booktabs}
- \usepackage{longtable}
- \usepackage{array}
- \usepackage{multirow}
- \usepackage[table]{xcolor}
- \usepackage{wrapfig}
- \usepackage{float}
- \usepackage{colortbl}
- \usepackage{pdflscape}
- \usepackage{tabu}
- \usepackage{threeparttable}
- \usepackage{threeparttablex}
- \usepackage[normalem]{ulem}
- \usepackage{makecell}
---
---
references:
- id: fenner2012a
title: One-click science marketing
container-title: Nature Materials
volume: 11
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Title
\begin{equation}
f\left(k\right)=\binom{n}{k}p^k\left(1-p\right)^{n-k} \label{eq:binom}
\end{equation}
You may refer to it using `\#ref(eq:binom)`, e.g., see Equation \#ref(eq:binom).
and not a nice citation! #fenner2012a
## Including Tables
You can also embed tables, for example: \#ref(tab:tw)
```{r tw, echo=FALSE}
mytable
```
## References
where mytable is stored in R session and is generated with
mytable <- head(cars) %>% kable(format = "latex",
booktabs = T,
caption = "Demo Table",
escape = F) %>%
kable_styling(latex_options = 'HOLD_position')
Now, this is supposed to work, but when I knit the document using
rmarkdown::render('C:\\Users\\john\\Documents\\bbv.Rmd')
the cross-reference for the table is not there! I only see ??
and the table has this weird #tab thing - how to get rid of it ?
the TOC is here even though I did not ask for it
Any ideas how to fix these issues?
Thanks!
EDIT: the weird #tab thing disappeared after a reboot.
The problem is that you are working against the intentions of kable by using it outside of an R chunk:
The kable() function will automatically generate a label for a table environment, which is the prefix tab: plus the chunk label.
https://bookdown.org/yihui/bookdown/tables.html
So the following workaround is definitely on the hacky side. Using a file foo.Rmd with
---
output:
bookdown::pdf_document2:
toc: no
header-includes:
- \usepackage{float}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Including Tables
You can also embed tables, for example: \#ref(tab:tw)
```{r tw, echo=FALSE}
mytable
```
You can also embed tables, for example: \#ref(tab:tw2)
```{r tw2, echo=FALSE}
mytable2
```
Referencing images is easier: \#ref(fig:plt)
```{r plt, echo=FALSE, fig.cap = 'hello', fig.height=3}
myplot
```
one can process this file with a second file foo.R:
library(knitr)
library(kableExtra)
# add the label to the options that would normally be populated from the chunk options
opts_current$append(list(label = "tw"))
mytable <- head(cars) %>% kable(format = "latex",
booktabs = T,
caption = "Demo Table",
escape = F) %>%
kable_styling(latex_options = 'HOLD_position')
opts_current$restore()
opts_current$append(list(label = "tw2"))
mytable2 <- tail(cars) %>% kable(format = "latex",
booktabs = T,
caption = "Demo Table",
escape = F) %>%
kable_styling(latex_options = 'HOLD_position')
opts_current$restore()
myplot <- ggplot(cars, aes(x = dist, y = speed)) + geom_point()
rmarkdown::render("foo.Rmd")
In principle, you can do these commands also just at the R prompt, but I try to not use the prompt directly. BTW, I do not get the (#tab) output with your code.
However, I think it makes more sense to not work against the workings of kable. I can understand that it can make sense to separate the data manipulation fro the presentation. However, creating the table is presentation from my point of view. So instead of creating the table externally I would just create the data externally. To make this concrete, let's use a file bar.Rmd:
---
output:
bookdown::pdf_document2:
toc: no
header-includes:
- \usepackage{float}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(kableExtra)
```
## Including Tables
You can also embed tables, for example: \#ref(tab:tw)
```{r tw, echo=FALSE}
mydata %>% kable(format = "latex",
booktabs = T,
caption = "Demo Table",
escape = F) %>%
kable_styling(latex_options = 'HOLD_position')
```
together with a file bar.R:
# insert data processing here
mydata <- head(cars)
rmarkdown::render("bar.Rmd")
This gives me the same output and the data processing is (initially!) separated from the presentation.

How to stop bookdown tables from floating to bottom of the page in pdf?

I am using bookdown to create pdf reports, but my tables are all floating down to the bottom of the page, regardless of how much space there is. See this example:
---
title: "test_doc"
author: "Jake Thompson"
date: "6/30/2017"
output:
bookdown::pdf_document2:
toc: false
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, collapse = TRUE)
library(tidyverse)
```
# Test heading
Let make a data frame and print it in Table \#ref(tab:test-table)
```{r test-table}
data_frame(col_a = seq_len(5), col_b = rnorm(5), col_c = runif(5)) %>%
knitr::kable(caption = "This is a test")
```
The resulting pdf looks like this:
Why does the table go to the bottom of the page? And is there a way to prevent this behavior?
You can solve this problem with kableExtra by
data_frame(col_a = seq_len(5), col_b = rnorm(5), col_c = runif(5)) %>%
knitr::kable(caption = "This is a test") %>%
kableExtra::kable_styling(latex_options = "hold_position")
It basically insert a [!h] to the LaTeX table environment which will prevent the floating behavior and pin the table at current location.
I had to use
kable_styling(latex_options = "HOLD_position")
Note the uppercase HOLD_position, different from hold_position. See also here.
To be able to use that, I also had to add to the top section of the doc (from How to build a latex kable through bookdown::render_book?):
output:
pdf_document:
extra_dependencies: ["float"]

R: why kable doesn't print inside a for loop?

I'm working a report with rmarkdown and latex. I need to print a group of tables using knitr::kable, but the don't print when inside a for loop.
This is my code:
---
title: "project title"
author: "Mr. Author"
date: "2016-08-30"
output:
pdf_document:
latex_engine: xelatex
bibliography: biblio.bib
header-includes:
- \usepackage{tcolorbox}
---
Text and chunks that run ok.
```{r loadLibraries}
require(data.table)
require(knitr)
```
## Try to print a group of tables from split
```{r results = "asis"}
t1 <- data.table(a = sample(letters, 10, T), b = sample(LETTERS[1:3], 10, T))
t2 <- split(t1, t1$b)
for (i in 1:length(t2)){
kable(t2[[i]], col.names = c("A", "B"))
}
```
It doesn't matter if I use results = "asis" or if I omit it altogether, nothing prints to the document.
I've tried enclosing the kable call within a print call (print(kable(t2[[i]]...), and it successfully prints the output to the document, but the format is the same format as a standard R prompt (preceded by ##, for example), which is rather ugly.
How can I display the tables, other than manually?
### EDIT ###
Some answerers have redirected me to R knitr print in a loop as a duplicate answer. It's not, because as I stated in the previous paragraph, this effectively prints the table, but the format is not the expected one. The accepted answer (and related github thread) really solved the problem.
This question is addressed here: https://github.com/yihui/knitr/issues/886
All you need is a line break after each print call
---
title: "project title"
author: "Mr. Author"
date: "2016-08-30"
output:
pdf_document:
latex_engine: xelatex
bibliography: biblio.bib
header-includes:
- \usepackage{tcolorbox}
---
Text and chunks that run ok.
```{r loadLibraries}
require(data.table)
require(knitr)
```
```{r results = "asis"}
t1 <- data.table(a = sample(letters, 10, T), b = sample(LETTERS[1:3], 10, T))
t2 <- split(t1, t1$b)
for (i in 1:length(t2)){
print(kable(t2[[i]], col.names = c("A", "B")))
cat("\n")
}
```

Resources