In rmarkdown (I happen to be using blogdown), if we use a SQL code chunk, a table caption is added with tab.cap in the knitr code chunk. Is there a way to use tab.cap for a R code chunk that prints a tibble using df_print = "kable" in the YAML.
I know that using the kable function directly would work, but I'm looking to use df_print.
```{r}
datasets::mtcars %>%
head(2) %>%
knitr::kable(caption = "My caption")
```
Reproducible Example
---
title: Table Captions
output:
blogdown::html_page:
df_print: "kable"
---
```{r setup, include = FALSE}
library(tidyverse)
library(DBI)
db <- dbConnect(RSQLite::SQLite(), dbname = "sql.sqlite")
```
```{sql, connection=db, tab.cap = "My Caption"}
WITH twoCol(a, b) AS (SELECT 1, 2 UNION SELECT 2, 4) SELECT a, b FROM twoCol;
```
```{r print-table, tab.cap = "Sample of the users table"}
datasets::mtcars %>%
head(2)
```
This is not mean to be an an answer, and I just want to show my own opinion.
df_print is used for printing data frames, and the output of your SQL code chunk is a SQL TABLE, not a data frame.
The chunk option tab.cap may just for SQL engine, which means we have to use function kable() directly to add table caption for data frame.
PS: As in the Section 1.5:
At the moment, not all features of rmarkdown::html_document are supported in
blogdown, such as df_print, code_folding, code_download, and so on.
However, I found that the df_print is supported in blogdown.
EDIT:
sql table is always printed with kable() no matter what df_print is. We can disable sql table caption by tab.cap = NA.
A table caption can be added by defining an chunk hook (e.g. table_caption). Insert the following code snippet at the top of the .rmd file (just a simple example):
```{r table_caption, echo = FALSE}
library(knitr)
knit_hooks$set(table_caption = function(before, options, envir) {
if(!before)
paste("<table><caption>", options$table_caption,
paste0("</caption><colgroup><col width='100'></col></colgroup>",
"<thead><tr class='header'></tr></thead><tbody></tbody></table><p>"),
sep = '')
else NULL
})
```
Then table captions can be added blow the tables.
```{sql, connection=db, tab.cap=NA, table_caption="sql table caption"}
WITH twoCol(a, b) AS (SELECT 1, 2 UNION SELECT 2, 4) SELECT a, b FROM twoCol;
```
```{r print-table, table_caption = "table caption"}
datasets::mtcars %>%
head(2)
```
`
Related
Is there a way to generate tables in a loop and set tab.id that can be later cross-referenced? Generating tables in a loop is trivial, but I don't know how to set ids and captions afterwards. Please, see the code below. Here I'm iterating over a list of R data.frames. In the last chunk I put the vector of ids (its lenght is 2) into chunk options - tab.id and tab.cap. This results in generation of two tables (good), but how to get the id of currently processed data.frame in the chunk?
---
output: officedown::rdocx_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}
library(flextable)
dfs <- list(
df1 = head(iris),
df2 = head(mtcars)
)
df_ids <- names(dfs)
```
```{r results='asis', tab.cap=paste("Result for item", df_ids), tab.id=paste0("tab_", df_ids),
tab.cap.style = "Table Caption"}
flextable(dfs[[???]]) # can current id be accessed somehow?
```
Another option is to use for loop to generate the tables. But how to set tab.id and tab.cap afterwards? Even a workaround solution can be fine for me.
You can probably set these values in a loop by using knitr::opts_chunk$set(). I would probably prefer set_caption in your case.
To print flextables in a loop inside an R Markdown document, use flextable_to_rmd(). See Looping in R Mardown documents.
---
output: officedown::rdocx_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}
library(flextable)
library(officer)
library(officedown)
library(magrittr)
dfs <- list(
df1 = head(iris),
df2 = head(mtcars)
)
df_ids <- names(dfs)
```
```{r results='asis'}
for(i in df_ids){
z <- flextable(dfs[[i]]) %>%
set_caption(caption = paste("Result for item", i),
style = "Table Caption",
autonum = run_autonum(seq_id = "tab", bkm = i))
flextable_to_rmd(z)
crossref_id <- sprintf("\\#ref(tab:%s)", i)
cat("\n\n\nA ref to table ", crossref_id, "\n\n\n\n")
}
```
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
In R markdown, I want to output a sortable table while the r chunk is set to results='asis'
DT::datatable yields the desired kind of output that I'm looking for. However that doesn't seem work with results='asis' set. I'm not sure if there's any kind of escape to this setting.
```{r setup, include=FALSE}
library(knitr)
my_data = mtcars
df_list = list()
df_list[[1]] = my_data[1:5,]
df_list[[2]] = my_data[6:10,]
### tabs {.tabset}
```{r, results='asis', echo = FALSE}
for (i in 1:length(df_list)){
cat("#### tab", i)
print(kable(df_list[[i]]))
cat('\n\n')
}
(*In the code above I had to omit the closing of r chunks "```" because I couldn't figure out how to properly display that in here)
As you can see, the second r chunk has results='asis' set. I'm setting it because I want to dynamically generate the tabs within the for loop. I'm printing the tables using print(kable...) but they are not sortable. Is there a way to output sortable tables once I have the file knitted? Thanks!
The DT renderer has to be initialized, as shown here and discussed more generally here:
---
title: "DT tabs"
output: html_document
---
```{r setup, include=FALSE}
library(knitr)
library(dplyr)
library(DT)
my_data = mtcars
df_list = list()
df_list[[1]] = my_data[1:5,]
df_list[[2]] = my_data[6:10,]
data.frame() %>%
DT::datatable() %>%
knitr::knit_print() %>%
attr('knit_meta') %>%
knitr::knit_meta_add() %>%
invisible()
```
### tabs {.tabset}
```{r, results='asis', echo = FALSE}
for (i in 1:length(df_list)){
cat("#### tab", i,'\n')
print(htmltools::tagList(DT::datatable(df_list[[i]])))
cat('\n\n')
}
Compiling a report with bookdown I encounter difficulties in referencing tables generated with the huxtable package. For my work, LaTex/PDF, as well as an HTML version of the report, need to be created.
When rendering the document knitr::is_XXX_output() selects the optimal way to display the tables, see MWE:
```{r chunk-label, results='asis', fig.cap='chunk-caption'}
set.seed(1234)
dat <- data.frame(cond = factor(rep(c("A","B"), each=2)),
rating = c(rnorm(2),rnorm(2, mean=.8)))
hux <- as_hux(dat) %>%
set_caption('hux caption') %>%
set_label("tab:hux-label")
if (knitr::is_html_output()) {
print_html(hux) # output table html friendly (requires in chunk options "results='asis'")
}
if (knitr::is_latex_output()) {
hux
}
```
I am not sure whether it is recommended to use the caption and label commands provided by huxtable
set_caption('pipe caption') and set_label("tab:hux-label")
or knitr
chunk-label and fig.cap='chunk caption'
For figures, the latter works very well, but unfortunately not for tables.
The hook for "tab.cap" as discussed in following did not work well with bookdown and if PDF & HTML are needed.
Using table caption on R markdown file using knitr to use in pandoc to convert to pdf
Help and recommendations are very much appreciated!
If you upgrade to huxtable 4.3.0 (now on CRAN), it automatically takes care of bookdown table captions for you. Here's a short example:
---
title: "Bookdown test"
output:
bookdown::pdf_book: default
link-citations: yes
---
```{r setup, include=FALSE}
library(dplyr)
library(huxtable)
knitr::opts_chunk$set(echo = FALSE)
```
My table is \#ref(tab:foo1). The other table is \#ref(tab:foo2). The third is \#ref(tab:foo3).
```{r}
hux(a = 1:5, b = 1:5) %>%
set_caption("My labelled table") %>%
set_label("tab:foo1")
hux(a = 1:5, b = 1:5) %>%
set_caption("My unlabelled table")
hux(a = 1:5, b = 1:5) %>%
set_caption("My labelled table, prefix should be autoadded!") %>%
set_label("foo2")
hux(a = "A table with no caption, but a label") %>%
set_label("tab:foo3")
hux(a = "A table with no caption or label")
```
Not everything is perfect. If you set echo = TRUE you will need to manually insert \usepackage[table]{xcolor} before \usepackage{fancyvry} in the TeX header.
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)