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().)
Related
I'd like to number my tables made with the gt package in rmarkdown rendered pdf.
What I've tried
In a markdown doc, defining a function f that increments a variable every time it is called:
---
title: "."
output: bookdown::pdf_document2
---
```{r}
library(gt)
.i <- 1
f <- function() {.i <<- .i + 1 ; as.character(.i)}
```
```{r numbered_kable}
knitr::kable(head(mtcars,2), caption = "bla")|> kableExtra::kable_styling(latex_options = "HOLD_position")
```
```{r numbered_but_ugly}
mtcars |> head(2) |>
gt() |>
tab_header(
glue::glue("{f()} blabla2")
)
```
Which works, but is a bit involved if both figures and tables need to be numbered.
Question
What is the best way to number figures and tables in using the gt package?
There is a cross-referencing version that seems to be working
devtools::install_github("rstudio/gt", ref="eff3be7384365a44459691e49b9b740420cd0851")
-markdown code
---
title: "."
output: bookdown::pdf_document2
---
```{r}
library(gt)
library(dplyr)
```
```{r numbered_gt}
mtcars %>%
head(2) %>%
gt() %>%
tab_header(title="blabla2",
label="tab:tab1")
```
-output
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
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
I'm doing a markdown report for my work. I need the outputs in word. Although with KABLE I can place titles on my tables, they are not numbered.
What should I add to kable () or in YAML to get automatic numbering of my tables?
crude example of what I do:
table(cars$speed) %>%
as.data.frame() %>%
kable(caption = "title",digits = 0, format.args = list( decimal.mark = ",",big.mark = "."),booktabs = T) %>%
kable_styling(latex_options = c("hold_position"))
To do this you will need to use the bookdown extensions to markdown. The following is an example rmarkdown (.Rmd) file which does want you want:
---
output:
bookdown::word_document2
---
See Table \#ref(tab:myfirsttable).
```{r myfirsttable, echo = FALSE}
knitr::kable(head(cars, 3), caption = "First three rows of cars dataset")
```
See Table \#ref(tab:mysecondtable).
```{r mysecondtable, echo = FALSE}
knitr::kable(head(iris, 3), caption = "First three rows of iris dataset")
```
Once generated the word document looks like:
For more information see:
https://bookdown.org/yihui/bookdown/a-single-document.html
https://bookdown.org/yihui/bookdown/tables.html
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")
```