How to view rendered kable in R Notebooks inline output? - r

I don't think I understand how table rendering works inline in R Notebooks, and how kable output is formatted inline as well.
I'd just like to be able to see dataframes in my notebook's inline output the way they appear when previewing the notebook / knitting the file.
What the table looks like in Notebook Preview:
I've tried turning off the paged print option, but still get it as seen below:
```{r results='asis', rmarkdown.df_print = FALSE}
ssc.sample.convert %>% tabyl(Role) %>% as.data.frame()
```
When attempting to use kable, I can't seem to get the output to look like it does in the rendered HTML file:
```{r results='asis', rmarkdown.df_print = FALSE}
ssc.sample.convert %>% tabyl(Role) %>% kable(format="html")
```
Is it possible to get rid of the paged print somehow?
Is it possible to view the final output of kable tables inline?

Related

Using Markdown formatting in table using kable in quarto

Using quarto's HMTL-output functionalities, I am trying to produce a kable from a data.frame that contains some Markdown-style formatting that should show up in the final document. In the actual use case, I have a number of documents already formatted this way and I would like re-use these commands for correctly rendering the output.
Here's my example.qmd:
---
title: "example"
format:
html
---
```{r setup}
library(kableExtra)
```
```{r}
#| echo: false
data.frame(Function = "`read_delim()`",
Formula = "$\\leftarrow$",
Break = "this continues on a<br>new line",
Link = "[Google](www.google.com)") |>
kbl(format = "html")
```
After running the chunk, the preview in RStudio does display the arrow and line break correctly, but ` ` and the link fail to have an effect:
When rendering the qmd to HTML, the result looks like this, i.e. ignores the formatting:
What am I missing? Is there a way to include such formatting commands into a kable when rendering a quarto document to HTML?
When creating a table in Quarto, you can't mix Markdown with HTML - the Markdown syntax won't be processed within the HTML table.
This R code would work
data.frame(Function = "`read_delim()`",
Formula = "$\\leftarrow$",
Break = "this continues on a<br>new line",
Link = "[Google](www.google.com)") |>
kbl(format = "markdown")
So if you can, output only Markdown table which knitr::kable() should do by default.
If you need to output a HTML table (e.g for specific HTML features), you need to use a framework that will render the markdown for you while creating the HTML table.
gt with fmt_markdown() and md()
flextable with ftextra and colformat_md() or as_paragraph_md
This is possible that this limitation of note being able to include raw Markdown inside HTML table will be improve in the future (https://github.com/quarto-dev/quarto-cli/discussions/957#discussioncomment-2807907)

How to add kableExtra table into RMarkdown Powerpoint slides

I'm attempting to add a table into an RMarkdown Powerpoint Presentation using the kableExtra package. Initially, I tried to run the code without always_use_html in my YAML and the following error appeared.
Error: Functions that produce HTML output found in document targeting pptx output.
Please change the output type of this document to HTML. Alternatively, you can allow
HTML output in non-HTML formats by adding this option to the YAML front-matter of
your rmarkdown file:
always_allow_html: true
Note however that the HTML output will not be visible in non-HTML formats.
Execution halted
After adding always_allow_html to my YAML, my table is still not appearing as desired in my slide .
My table should look something like this
Does anyone perhaps know how to embed a kableExtra table in Rmarkdown slides?
Here is my full code
---
title: "Untitled"
output: powerpoint_presentation
always_use_html: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
## Table
```{r table}
library(kableExtra)
data <- data.frame(a = c(1,2,3), b = c(4,5,6))
data %>%
kable() %>%
kable_styling()
```
Try kbl() instead of kable():
library(kableExtra)
data <- data.frame(a = c(1,2,3), b = c(4,5,6))
data %>%
kbl() %>%
kable_styling()
kable() renders to html in the viewer pane when run live, and can knit to html.
Office docs don't handle the html.
Options
include, pass a table to the default powerpoint style for your document with .rmd.
See:https://support.rstudio.com/hc/en-us/articles/360004672913-Rendering-PowerPoint-Presentations-with-the-RStudio-IDE
use officer with officemarkdown
Officer bookdown summary
-advanced styling to build a custom template can be done for reproducible
-you can save to powerpoint, then use table style editing to tweak, vs. setting the styling with style_type, style_id,style_name parameters in officedown

How can I use kable or any other table package as default in Rmarkdown rendering

I am pretty sure that I've seen that it was possible to setup kable or some other Rstudio-supported table package as default when I rmarkdown:::render a Rmd document.
I cannot find if this is a yaml option or something that can be knitr::opts_chunk$set()
What I want is to stop having to do
```{r}
table = f()
table %>% head() %>% kable(table) # or something equivalent so the table is 'nicely' displayed
```
It depends on your output format (which you didn't mention). For example, for html_document, there is a df_print option, and you can set it to kable.

Format text inside R code chunk

I am making some slides inside Rstudio following instructions here:
http://rmarkdown.rstudio.com/beamer_presentation_format.html
How do I define text size, colors, and "flow" following numbers into two columns?
```{r,results='asis', echo=FALSE}
rd <- sample(x=1e6:1e7, size = 10, replace = FALSE)
cat(rd, sep = "\n")
```
Output is either HTML (ioslides) or PDF (Beamer)
Update:
Currently the code above will only give something like the following
6683209
1268680
8412827
9688104
6958695
9655315
3255629
8754025
3775265
2810182
I can't do anything to change text size, color or put them into a table. The output of R codechunk is just plain text. Maybe it is possible to put them in a table indeed, as mentioned at this post:
http://tex.aspcode.net/view/635399273629833626273734/dynamically-format-labelscolumns-of-a-latex-table-generated-in-rknitrxtable
But I don't know about text size and color.
Update 2:
The idea weaving native HTML code to R output is very useful. I haven't thought of that. This however only works if I want to output HTML. For PDF output, I have to weave the native Latex code with R output. For example, the code following works using "knitr PDF" output:
```{r,results='asis', echo=FALSE}
cat("\\textcolor{blue}{")
rd <- sample(x=1e6:1e7, size = 10, replace = FALSE)
for (n in rd) {
cat(paste0(n, '\\newline \n')) }
cat("}")
```
You are using results='asis', hence, you can simply use print() and formatting markup. If you want your text to be red, simply do:
```{r,results='asis', echo=FALSE}
print("<div class='red2'>")
rd <- sample(x=1e6:1e7, size = 10, replace = FALSE)
cat(rd, sep = "\n")
print("</div>")
```
Hope it helps.
It sounds as if you want the output to be either PDF or HTML.
One possibility is the xtable package. It produces tables either in PDF or HTML format. There's no (output-independent) way to specify colour, however. Here's an example.
xt <- xtable(data.frame(a=1:10))
print(xt, type="html")
print(xt) # Latex default
Another option is the pandoc.table function from the pander package. You need the pandoc binary installed. If you have RStudio, you have this already. The function spits out some markdown which then can be converted to HTML or PDF by pandoc.
Here's how you could use this from RStudio. Create an RMarkdown document like this:
---
title: "Untitled"
author: "You"
date: "20 November 2014"
output: html_document
---
```{r, results='asis'}
library(pander)
tmp <- data.frame(a=1:10,b=1:10)
pandoc.table(tmp)
```
When you click "knit HTML", it will spit out a nice HTML document. If you change output to pdf_document, it will spit out a nice PDF. You can edit the options to change output - e.g.
pandoc.table(tmp, emphasize.strong.rows=c(2,4,6,8,10))
and this will work both in PDF or HTML. (Still no options to change colour though. Homework task: fix pandoc.table to allow arbitrary colours.)
Under the hood, knitr is writing markdown, and pandoc is converting the markdown to whatever you like.

Rotate a table from R markdown in pdf

I'm writing in R Markdown and have a contingency table that is quite wide. I am converting the R markdown document to a PDF using pandoc.
Is it possible to rotate or shrink the table? Ideally this would be done without having to switch to LaTeX formatting.
My Attempts:
I've been abusing the figure options in knitr to attempt this, but whether I use kable or xtable, I haven't had any luck. Some permutations I have tried include:
```{r out.extra='angle=90', results='asis'}
library(knitr)
kable(iris[1:5,])
```
``{r size='footnotesize', results='asis'}
library(knitr)
kable(iris[1:5,])
```
```{r out.extra='angle=90', results='asis'}
library(xtable)
xtable(iris[1:5,])
```
```{r size='footnotesize', results='asis'}
library(xtable)
xtable(iris[1:5,])
```
All of these show the table nicely, but do not rotate it.
The code I'm using to knit is:
Rscript -e "library(knitr); knit('table.Rmd', 'table.md')"
And to convert to pdf:
pandoc table.md -o table.pdf
The out.extra='angle=90' only works on Figures, and unfortunately not tables. Here are several potential approaches:
KableExtra (Rotate Page)
You can easily rotate tables using the useful addon package kableExtra. Specifically, the landscape() function will put the table on an single landscape page. It’s useful for wide tables that can’t
be printed on a portrait page.
library(kableExtra)
kable(iris[1:5,],
format = "latex", booktabs = TRUE) %>%
kableExtra::landscape()
The limitation of these function is that it does force a new page, so depending on the size of your table it could leave a bit of blank space.
KableExtra (Scale Width)
You can scale the width of the table using the function kable_styling(latex_options = "scale_down"). This will force the table to the width of the page.
kable(iris[1:5,],
format = "latex", booktabs = TRUE) %>%
kable_styling(latex_options = "scale_down")
For more examples of the kableExtra package, check out the package here: https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf
Stargazer (Rotate Table)
Other options are available, but these largely require the installation of additional LaTeX packages. For example, the stargazer package can print tables in landscape using the float.env argument:
```{r, results="asis"}
stargazer(iris[1:5,],
float.env = "sidewaystable")
```
This requires \usepackage{dcolumn} in LaTeX preamble
Read more about customising your LaTex preamble here: https://tex.stackexchange.com/questions/171711/how-to-include-latex-package-in-r-markdown
You can add some LATEX code in your Rmd file :
\usepackage{lscape}
\usepackage{pdfpages}
Some text on a portrait page.
\newpage
\blandscape
## Title, lorem ipsum
```{r, results = "asis"}
kable(iris[1:5,], caption = "Lorem again")
```
Lorem ipsum...
\elandscape
Some other text on a portrait page.
Can you just use t()?
library(xtable)
xtable(t(iris[1:5,]))
If your table is still to long, split it up into multiple tables. e.g.:
splits = floor(seq(1, ncol(iris), length=5))
for(i in 2:length(splits)){
mini.tab = iris[ , splits[i-1]:splits[i]]
xtable(mini.tab)
}

Resources