In RMarkdown, why is the kable table printing below the header here? - r

I'm trying to generate a report with each row of a tibble printing vertically in a table on its own page using a for loop. The tables are printing fine, but I want to put headers at the top of each page (and eventually, text). Since the line of code to print the header (which appears as a header in my own document but not in my reprex, not sure why) is above the line of code to print the table, using kable, I expect the header to print above the table. I suspect kable is doing something I don't understand behind the scenes but I cannot determine what.
What am I doing wrong, and how may I print headers at the top of each page?
I've provided below: a screenshot of the current output.
Relevant portion:
---
title: "kable-order-reprex"
author: "Rob Creel"
date: "6/4/2021"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(magrittr)
library(kableExtra)
```
```{r chunk1, echo=FALSE, results='asis'}
for (i in 1:nrow(mtcars)) {
# Generate Table
mtcars %>%
slice(1) %>%
stack() %>%
select(ind, values) %>%
kable(col.names = NULL) %>%
kable_styling() -> my_table
cat("\n\n\\pagebreak\n")
# Print Header
cat(paste0("## ", mtcars %>% rownames() %>% extract2(i)))
# Print Table
print(my_table)
cat("\n\n\\pagebreak\n")
}
```
Pic of mis-ordered output.:

As far as I can tell everything is working as intented. The problem is float management in LaTeX.
You can change the behaviour of the kable output by setting the argument latex_options in kable_styling(). E.g.
mtcars %>%
slice(1) %>%
stack() %>%
select(ind, values) %>%
kable(col.names = NULL) %>%
#Use either "hold_position" or "HOLD_position"
kable_styling(latex_options = "hold_position") -> my_table
hold_position corresponds to h, while HOLD_position is H, (read more about float options here), where H is stricter than h and forces the position of the float output to be at the position where it is in the code. Also see ?kable_styling (latex_options entry)
See similar question with answer here

Related

how to use gt::as_word output in a quarto file

The {{gt}} package now includes a function as_word, which outputs the table as an OOXML string.
I would like to use this to insert tables into the word output of a Quarto document.
I thought this would work.
---
title: "Untitled"
format: docx
---
```{r}
library(gt)
gtcars %>%
dplyr::select(mfr, model) %>%
dplyr::slice(1:2) %>%
gt() %>%
tab_header(
title = md("Data listing from **gtcars**"),
subtitle = md("`gtcars` is an R dataset")
) %>%
as_word()
```
But the word output is just the OOXML string, like this. How can I make the table appear as a table in the quarto word output?
No need to print an OOXML string for this purpose I guess – it works with the print() method for docx output:
```{r, echo=F}
library(gt)
gtcars %>%
dplyr::select(mfr, model) %>%
dplyr::slice(1:2) %>%
gt() %>%
tab_header(
title = "Data listing from gtcars",
subtitle = "gtcars is an R dataset"
)
```
(There's some trouble with the markdown code though, probably a bug. I've removed md().)

How to embed escape characters ("\n", "\t") into dataframe?

How to insert escape characters into dataframe?
It will be useful for the formatting of text data into table packages.
We could be use one universal solution for every table package (my hope).
But now we should employ a lot of approaches for the every case (depends on libraries and output formates: pdf, html).
It is really uncomfortable!
For example, we have next data
df <- data.frame("names" = c("a long long long long long ... pretty long name of the our story","Here is also long, but a little shorter"))
We see a normal output
names
1 a long long long long long ... pretty long name of the our story
2 Here is also long, but a little shorter
But how we can achieve this output ("\n")?
names
1 a long long long long long
... pretty long name of the our story
2 Here is also long, but a little shorter
I promised to add a simple example:
knit to HTML, in PDF doesn't work
```{r warning = FALSE, echo = FALSE, message=FALSE, include=FALSE,}
library(flextable)
library(gt)
#data
df <- data.frame("names" = c("a long long long \n long long ... <br> pretty long name of the our story","Here is also long, but a little shorter"))
#table one
table3 <- flextable(df)
table3 <- set_table_properties(table3, layout = "autofit", width = .5)
table3
#table two
table4 <- gt(df) %>% fmt_markdown(columns = everything())
table4
```
<center>
<caption>Table in flextable </caption>
</center>
`r table3`
<center>
<caption>Table in gt </caption>
</center>
`r table4`
In the first case - works \n, in the second - /br/ and there are only two packages!
Don't add any line breaks to your text!! This is absolutely unnecessary. All you need is the skillful use of the kableExtra package. Note the code below is the content from the RMarkdown.
The document created with it can be found here.
Add everything from ## RMarkdown Start to ## RMarkdown End to RMarkdown
Of course, don't forget to remove the comment characters before the code blocks (#```)!!
## RMarkdown Start
---
title: "LongText"
author: "Marek Fiołka"
date: "30 11 2021"
output:
html_document: default
pdf_document: default
---
#```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
#```
Prepare data frame with long text
#```{r echo=TRUE, message=FALSE, warning=FALSE}
library(stringi)
library(tidyverse)
library(kableExtra)
n=50
df = tibble(
id = 1:n,
txt = stri_rand_lipsum(n)
)
#```
See the data frame in a typical display
#```{r}
print(df)
#```
View data frame formatted with Kable Extra for HTML
#```{r}
df %>% kbl() %>%
kable_styling()
#```
View data frame formatted with Kable Extra for PDF
#```{r}
df %>% kbl() %>%
kable_paper(full_width = F) %>%
column_spec(1, bold = T, border_right = T) %>%
column_spec(2, width = "30em")
## RMarkdown End
This way you can create not only html documents but also corresponding pdf documents. Below is a fragment of a document created in this format. Note that in this case you have to use kable_paper with column_spec instead of kable_styling.
Hope this is what you were looking for.
Update
## RMarkdown Start
---
title: "LongText"
author: "Marek Fiołka"
date: "30 11 2021"
output:
pdf_document: default
html_document: default
---
#```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
#```
Prepare data frame with long text
#```{r echo=TRUE, message=FALSE, warning=FALSE}
library(stringi)
library(tidyverse)
library(kableExtra)
n=10
df = tibble(
id = 1:n,
txt = stri_rand_lipsum(n)
)
#```
See the data frame in a typical display
#```{r echo=TRUE}
print(df)
#```
View data frame formatted with [kableExtra](http://haozhu233.github.io/kableExtra/) for HTML
#```{r}
df %>% kbl() %>%
kable_styling()
#```
View data frame formatted with [kableExtra](http://haozhu233.github.io/kableExtra/) for PDF
#```{r}
df %>% kbl() %>%
kable_paper(full_width = F) %>%
column_spec(1, bold = T, border_right = T) %>%
column_spec(2, width = "30em")
#```
View data frame formatted with [gt](https://gt.rstudio.com/index.html) (only for HTML)
#```{r}
library(gt)
df %>% gt %>%
fmt_markdown(columns = everything()) %>%
tab_options(table.width = px(400))
#```
View data frame formatted with [flextable](https://davidgohel.github.io/flextable/articles/overview.html) HTML & PDF
#```{r message=FALSE, warning=FALSE}
library(flextable)
df %>% flextable %>% width(2, width = 6, unit = "in")
#```
View data frame formatted with [huxtable](https://hughjonesd.github.io/huxtable/) HTML & PDF
#```{r message=FALSE, warning=FALSE}
library(huxtable)
df %>% as_hux %>%
set_width(1) %>%
set_right_border(everywhere, 1, brdr(3, "double", "grey"))
#```
## RMarkdown End

How to print PDF tables created with kable in landscape layout with a caption?

Context: I am knitting an Rmarkdown report mixing landscape and portrait layouts. I use the technique described here: https://stackoverflow.com/a/41945462/10264278.
Problem: there is an unexpected table layout problem. when the table is made using kableExtra::kable() it does not follow the expected orientationif a caption is filled in kable(caption =...).
Reproducible example:
---
output: pdf_document
header-includes:
- \usepackage{pdflscape}
- \newcommand{\blandscape}{\begin{landscape}}
- \newcommand{\elandscape}{\end{landscape}}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo=FALSE, warning=FALSE, comment=FALSE, message=FALSE)
library(dplyr)
library(kableExtra)
```
\blandscape
```{r}
mtcars # displays properly
mtcars %>% kable(caption = "test", digits = 2) # the table follows the landscape layout and does not remains "still"/"horizontal"
```
\elandscape
The output:
Table on the left (mtcars) is displayed as expected. But, if I use kable() the table "turns with the page" witch is not expected.
EDIT:
I am aware that kableExtra::landscape() exists. But this function creates a new page for each table. Here I have many few-rows tables that are very wide. Thus I do not want to have a single table per page.
Example:
```{r}
head(mtcars, 5) %>% kable(caption = "test", digits = 2) %>% landscape(margin = NULL)
head(mtcars, 5) %>% kable(caption = "test", digits = 2) %>% landscape(margin = NULL)
```
Output:
EDIT 2:
This problem occurs only if a caption is specified in kable(caption = ...).
Example:
\blandscape
```{r}
mtcars # displays properly
mtcars %>% kable(digits = 2) # the table follows the landscape layout and does not remains "still"/"horizontal"
```
\elandscape
Output:

Redering bold header in markdown after kable

If I knit a document to md using kable("html") for a table and load it up to GitHub the bold header will not be rendered after the chunk.
```{r}
library(knitr)
library(dplyr)
iris %>%
group_by(Species) %>%
summarise(n = n()) %>%
kable("html")
```
Some Header (This is not bold in the final document: used ** **)
... next chunk.
```[r}
iris %>%
distinct(Species)
````
Some Header 2 (This is bold in the final document: used ** **)
You mean a code chunk like this:
knitr::kable(head(iris),caption = "iris dataset",format = "html")
bold
Also:
-kable is part of knitr (or perhaps kableExtra), not a package in itself. Please check.
-Check extra ")" in summarise(n = n))

how can I show my "ztable" when I use "knit to HTML" in R?

I am having a problem with my ztable,
I want to knit my Rmarkdown file to HTML but I cannot find a way to display the table I created with ztable:
z=ztable(loucaste) %>% makeHeatmap(palette = "Blues") %>% print(caption="Table 2.)
I tried to set
options(ztable.table="html")
and put this at the beginning as I read somewhere else
output: html_document
header-includes: \usepackage{colortbl}
but it doesn't work when I knit to HTML. My intention was to create a sort of formatting table similar to the ones made on excel and ztable looks like the only way.
Try this minimal Rmd. The key seems to be options(ztable.type = "html") and in the chunk that generates the table, r results='asis'
If that works for you, substitute your code in the appropriate place i.e. ztable(loucaste) %>% makeHeatmap(palette = "Blues") %>% print(caption="Table 2.).
---
title: "ztable"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ztable)
library(magrittr)
options(ztable.type = "html")
```
## R Markdown
```{r results='asis'}
matrix(1:100, nrow = 10) %>%
as.data.frame() %>%
ztable() %>%
makeHeatmap() %>%
print(caption = "table 2")
```

Resources