Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does kable not print when used within a function in rmarkdown

I have to repeat certain outputs in many rmarkdown reports and want to write a function to use for this.

Calling a function outputs plots ok when I knit the rmd file but not kable data frames.

For example

---
title: "Markdown example"
output: html_document
---

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

# Markdown example
```{r mtcars}
make_outputs <- function(){
  knitr::kable(head(mtcars))
  plot(mtcars$mpg, mtcars$cyl)
  hist(mtcars$cyl)
}

make_outputs()

```

Displays the plots but not the kable table.

like image 369
pav Avatar asked Feb 03 '17 12:02

pav


People also ask

What does Kable function do in R?

The kable() function in knitr is a very simple table generator, and is simple by design. It only generates tables for strictly rectangular data such as matrices and data frames. You cannot heavily format the table cells or merge cells.

How do you display output but hide code in R Markdown?

Chunk options For example, echo=FALSE indicates that the code will not be shown in the final document (though any results/output would still be displayed). You use results="hide" to hide the results/output (but here the code would still be displayed).

How do you show results in R Markdown?

If you prefer to use the console by default for all your R Markdown documents (restoring the behavior in previous versions of RStudio), you can make Chunk Output in Console the default: Tools -> Options -> R Markdown -> Show output inline for all R Markdown documents .

Why is my R Markdown not knitting?

No Knit HTML button This means that RStudio doesn't understand your document is supposed to be an RMarkdown document, often because your file extension is . txt . To fix this, go to the Files tab (lower right corner, same pane as Plots and Help) and select the checkbox next to your document's name.


1 Answers

You can do this by using print to print the kable output, setting the results="asis" of the code chunk and then using kable_styling from package kableExtra.

This works for me:

```{r mtcars, results='asis'}

library(kableExtra)
library(knitr)

make_outputs <- function(){
  print(kable_styling(kable(head(mtcars))))
  plot(mtcars$mpg, mtcars$cyl)
  hist(mtcars$cyl)
}

make_outputs()
```
like image 95
George Savva Avatar answered Sep 28 '22 04:09

George Savva