Using Markdown formatting in table using kable in quarto - r

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)

Related

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

Is there a way to add line breaks ONLY when exporting to PDF in R Markdown?

I think the question is quite self-explanatory but for avoidance of doubt I'll explain with more detail below:
I have an R Markdown document that works well if converted to HTML or uploaded to GitHub. When converting to PDF (using Latex), the results are not so pretty. I find that the biggest problem in a Latex PDF document are line breaks. I can fix the line breaks issue on the PDF document by adding "\ " characters, but that throws my HTML document out of whack too.
Is there a way to manually add line breaks (or "space before/after paragraphs") for the PDF output only?
Thank you!
You can redefine the relevant spacings in the YAML header. \parskip controls the paragraph spacing. Code blocks are shaded using a snugshade environment from the framed package. We can also redefine the shaded environment for code blocks to have some vertical space at the start. Here's a reproducible example. Note: I also added the keep_tex parameter so you can see exactly what the generated tex file looks like, in case this is useful:
title: "test"
author: "A.N. Other"
header-includes:
- \setlength{\parskip}{\baselineskip}
- \renewenvironment{Shaded}{\vspace{\parskip}\begin{snugshade}}{\end{snugshade}}
output:
pdf_document:
keep_tex: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
Once you output to HTML, you can just print the HTML webpage as PDF. that might be an easy way keep the original format

How to view rendered kable in R Notebooks inline output?

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?

How to replicate Knit HTML in a command line?

I know this question is similar to this one. But I couldn't get a solution there so posting it here again.
I want to get the exact same output as I get by clicking "Knit HTML" but via a command. I tryied using knit2html but it messes with the formatting and does not include the title, kable does not work etc.
Example:
This is my test.Rmd file,
---
title: "test"
output: html_document
---
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r}
library(knitr,quietly=T)
kable(summary(cars))
```
You can also embed plots, for example:
```{r, echo=FALSE}
plot(cars)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
Output:
Knit HTML
knit2html
The documentation tells us:
If you are not using RStudio then you simply need to call the rmarkdown::render function, for example:
rmarkdown::render("input.Rmd")
Note that in the case using the “Knit” button in RStudio the basic mechanism is the same (RStudio calls the rmarkdown::render function under the hood).
In essence, rmarkdown::render does a lot more setup than knitr::knit2html, although I don’t have an exhaustive list of all differences.
The most flexible way of rendering the output is, at any rate, to supply your own stylesheet to format the output according to your wishes.
Please note that you need to set up Pandoc manually to work with rmarkdown::render on the command line.
That said, here are two remarks that would improve the knitr::knit2hmtl output, and that are superior to using rmarkdown::render in my opinion:
To include the title, use a Markdown title tag, not a YAML tag:
# My title
To format tables, don’t use the raw kable function. In fact, this is also true when using rmarkdown::render: the alignment of the table cells is completely off. Rmarkdown apparently uses centering as the default alignment but this option is almost never correct. Instead, you should left-align text and (generally) right-align numbers. As of this writing, Knitr cannot do this automatically (as far as I know) but it’s fairly easy to include a filter to do this for you:
```{r echo=FALSE}
library(pander)
# Use this option if you don’t want tables to be split
panderOptions('table.split.table', Inf)
# Auto-adjust the table column alignment depending on data type.
alignment = function (...) UseMethod('alignment')
alignment.default = function (...) 'left'
alignment.integer = function (...) 'right'
alignment.numeric = function (...) 'right'
# Enable automatic table reformatting.
opts_chunk$set(render = function (object, ...) {
if (is.data.frame(object) ||
is.matrix(object)) {
# Replicate pander’s behaviour concerning row names
rn = rownames(object)
justify = c(if (is.null(rn) || length(rn) == 0 ||
(rn == 1 : nrow(object))) NULL else 'left',
sapply(object, alignment))
pander(object, style = 'rmarkdown', justify = justify)
}
else if (isS4(object))
show(object)
else
print(object)
})
```

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.

Resources