Atanas Janackovski
Atanas Janackovski

Reputation: 368

Conitional output style of kable/kableExtra

Is there any ability to write a function to export kable or kableExtra tables as different formats based on the output that knitr creates.

Specifically, I would want format = "simple" for .docx and format = "html" for .html.

I cannot find any examples of this so not sure if it is not possible.

Upvotes: 2

Views: 295

Answers (3)

Atanas Janackovski
Atanas Janackovski

Reputation: 368

Okay, so thanks to @bttomio's answer, I figured out a solution that will work...

## set options for knitr
options(
  knitr.table.format = ifelse(knitr::pandoc_to("docx"), "simple", "html")
)

## create var to call
kbl_frmt <- getOption("knitr.table.format")

Then when generating a table, something like:

kbl(
  df,
  format = kbl_frmt,
  etc...
)

Which from my tests formats the tables based on the format outputted by knitr. There may be a more elegant solution, but at least was I only have to write code for one table.

Upvotes: 1

bttomio
bttomio

Reputation: 2306

Maybe this could be helpful (eval=knitr::is_html_output() for the html chunk):

---
title: "Untitled"
output:
  html_document: default
  word_document: default
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = F)
library(kableExtra)
```

## Conditional

```{r html, eval=knitr::is_html_output()}
dt <- mtcars[1:5, 1:6]
kbl(dt, "html", booktabs = T)
```

```{r docx}
dt <- mtcars[1:5, 1:6]
kbl(dt, "simple", booktabs = T)
```

Upvotes: 1

MaxMiak
MaxMiak

Reputation: 197

I think this may help you in case you want to export your table in different format use datatable it is more flexible than kable and short hint will be as below:

datatable(your dataframe, extenions=c('Buttons'),
#list column names to be displayed in the table
colnames=c("col1","col2",etc..),
options = list(
pageLength = 400,
dom = 'Bfrtip',
buttons = c('copy', 'csv', 'excel', 'pdf', 'print'),
columnDefs = list(list(className = 'dt-center', targets = 2:7))
                )
)

After above code your table will be downloadable in mention formats

Upvotes: 0

Related Questions