How to set df_print to tibble in markdown for a single R code chunk - r-markdown

I would like to show, in an rmarkdown document, the printed output of a tibble as shown in the console. i.e.
First line: dimension summary;
then the column headers;
then classes of variables;
then first 10 lines of the tibble;
then number of rows not shown.
However, by default, tibbles and other data.frame objects are automatically converted to a tabbed, paginated table showing all contents.
I note that the option to turn off this default behaviour can be set for a whole markdown document by changing the df_print option to tibble in the YAML.
However, how do I set the df_print option to tibble for just a single R code chunk, so that I can show in an Rmarkdown document what the user will see on the console?
Thanks,
Jon

There's no need to touch the global setting. You can explicitly call the print function tibble:::print.tbl_df(df)
Example:
title: "Untitled"
author: "TC"
date: "7/27/2018"
output:
html_document:
df_print: "kable"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## print tibble
```{r}
df <- tibble::as.tibble(mtcars)
tibble:::print.tbl_df(head(df))
```
## print kable (set in YAML header)
```{r}
head(df)
```
output html

Related

How to PDF render Quarto books with dynamic content?

I am writing my thesis using a Quarto book in HTML, which has some dynamic content (leaflet maps, plotly dynamic graphs). However, eventually, I will need to export the book in PDF/LaTeX, or at least Word (and then I can copy and paste into LaTeX).
When I try to export to PDF I of course run into this error:
Functions that produce HTML output found in document targeting pdf
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.
I did try to add the always_allow_html: true in my YAML file, but I get the same exact error. I also tried the conditional rendering with {.content-hidden unless-format="pdf"}, but I can't seem to get it working.
Has anyone experienced the same issue?
Using .content-visible when-format="html" and .content-visible when-format="pdf" works very smoothly.
---
title: "Conditional Rendering"
format:
html: default
pdf: default
---
## Conditional Content in Quarto
::: {.content-visible when-format="html"}
```{r}
#| message: false
library(plotly)
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p <- p + geom_point(aes(colour = factor(cyl)))
ggplotly(p)
```
```{r}
#| message: false
#| fig-pos: "H"
#| fig-width: 4
#| fig-height: 3
library(leaflet)
# took this example from leaflet docs
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
m # Print the map
```
:::
::: {.content-visible when-format="pdf"}
```{r}
library(plotly)
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p <- p + geom_point(aes(colour = factor(cyl)))
p
```
:::
I use constructs like below
p <- ggplot()
if (interactive() || opts_knit$get("rmarkdown.pandoc.to") == "html") {
ggplotly(p)
} else {
p
}
Stumbled across this one too. I'm currently checking the output format of pandoc globally
```{r, echo = F}
output <- knitr::opts_knit$get("rmarkdown.pandoc.to")
```
and then evaluate chunks conditionally:
(leaflet example from here.)
```{r, echo = F, eval = output != "latex"}
library(leaflet)
leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
```
This is optional if you want a note on a missing component in the PDF version:
```{r, echo = F, eval = output == "latex", results = "asis"}
cat("\\textit{Please see the HTML version for interactive content.}")
```
Edit
I just checked, this also works with Quarto documents for me using the below YAML header.
---
title: "Untitled"
format:
html:
theme: cosmo
pdf:
documentclass: scrreprt
---

How to create own table in Bookdown and reference it within the text?

I am currently writing my thesis in RMarkdown using the template Oxforddown (which is ultimately based on bookdown). I have been reading the documentation but I confess I am lost. I am trying to create a table that contains an overview of the experimental conditions and items I used in my empirical study, so it is not data that I can load into R and then use the kable function on. However, I do not understand how I could generate such a table. Generating RMarkdown tables outside code chunks seems to work, but then the captions and referencing are very different than the rest of the captions used so far, which I usually set up within code chunks. Example below:
{r pilot-short7, echo=FALSE, fig.scap="Pilot 2: ....", out.width="65%", message=FALSE, fig.pos='H', fig.align = 'center'}
When I am trying to include RMarkdown tables inside a code chunks, things go wrong. What would my options be?
Any help would be very much appreciated!
I prepared a markdown template for you.
Here I made a table with flextable library.
But you can use another, which you like, f.e.: kableExtra, gt etc.
As you can see, you should put \label{tab:caption} and after refer in the text by \ref{tab:caption}.
---
title: "Hello World"
header-includes:
- \usepackage{caption}
output:
pdf_document:
latex_engine: xelatex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, include = FALSE}
library(flextable)
library(dplyr)
table2 <- flextable(mtcars[1:5, 1:6])
```
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:
\begin{table}[hbtp]
\captionof{table}{Text of the caption.}
\label{tab:caption}
`r table2`
\end{table}
Table \ref{tab:caption} is the baddest table in the World

Evaluate a Rmarkdown codechunk only for certain document type (html_document vs pdf_document)

I'd like to add an interactive map (a leaflet) to my HTML document, but this can't be done in a PDF document since they are static.
I know that Rmarkdown can choose to evaluate a chunk depending on a global variable, like this:
```{r setup}
ev_cars = TRUE
```
## First chunk
```{r cars, eval=ev_cars}
summary(cars)
```
I guess my question is "does knitr set a global variable indicating whether it is knitting an html_document or a pdf_document" ?
thanks
knitr::is_latex_output() and knitr::is_html_output do that job.
ref: https://bookdown.org/yihui/rmarkdown-cookbook/latex-html.html

Adding a letter to all table numbers in RMarkdown

I'm using RMarkdown to create Supplementary documents for a paper. These supplements contain many tables. Let's call these documents Supplement A and Supplement B. I want the table numbering to reflect the supplement letter, that is, Table A1 or Table 1A for the first table in Supplement A and so on for all tables.
How can I modify the table numbering to add a letter into the table numbering schema?
Here's an example that will produce a table with normal numbering:
---
title: "Supplement A"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
```
```{r cars}
kable(mtcars[1:5, ], booktabs=TRUE, caption="MTCars") %>%
kable_styling(latex_options="hold_position", position="left")
```
An inelegant solution using the captioner package (details provided here: https://datascienceplus.com/r-markdown-how-to-number-and-reference-tables/) can create captions and insert them manually just before the code chunk. Combining this with the Latex package caption makes it possible to remove the automatic table naming and numbering if the caption is generated within the code chunk (How to suppress automatic table name and number in an .Rmd file using xtable or knitr::kable?). I've done this in the YAML with \captionsetup[table]{labelformat=empty}, but it can be done in the document body also. Either way, the caption can then be generated within the code chunk, which was important in my case.
This solution stops bookdown referencing from working (because labelformat cannot be empty), but a workaround for table referencing was provided in the link for using the captioner package (and is included below).
---
title: "Supplement A"
header-includes:
- \usepackage{caption}
\captionsetup[table]{labelformat=empty}
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
library(captioner)
library(stringr)
```
```{r captions}
# Create the caption(s)
caption <- captioner("Table A", FALSE)
tab_1_cap <- caption("Tab_1", "MTCars")
# Create a function for referring to the tables in text
ref <- function(x) str_extract(x, "[^:]*")
```
The following table is `r ref(tab_1_cap)`.
```{r cars}
kable(mtcars[1:5, ], booktabs=TRUE, caption=tab_1_cap) %>%
kable_styling(latex_options="hold_position", position="left")
```
An alternative solution is avaiable via LaTeX. Add the following somewhere in the body of the document to change the default figure and table names to include the letter.
\def\figurename{Figure A}
\def\tablename{Table A}
To reference a table or figure in text use, e.g., Table A\#ref(tab:label), after defining the table label as normal.
This alone will leave a space in the table/figure caption (e.g., 'Table A 1' instead of 'Table A1'). This can be solved by adding the following to the YAML:
header-includes:
- \usepackage{caption}
- \DeclareCaptionLabelFormat{nospace}{#1#2}
- \captionsetup[figure]{labelformat=nospace}
- \captionsetup[table]{labelformat=nospace}
The \DeclareCaptionLabelFormat creates a function (here labeled nospace), which overrides the default caption label when called. #1 represents the label assigned to refer to tables or figures (e.g., 'Table A') and #2 represents the number of the table or figure. The captionsetup lines change the label format for all tables and figures to the format defined by 'nospace'.
Thus, the code produces, e.g., 'Table A1: Table name' as the caption. If instead you wanted, e.g., 'Table A-1: Table name', the code in \DeclareCaptionLabelFormat should be changed to {#1-#2}.
---
title: "Supplement A"
output: bookdown::pdf_document2
toc: false
header-includes:
- \usepackage{caption}
- \DeclareCaptionLabelFormat{nospace}{#1#2}
- \captionsetup[figure]{labelformat=nospace}
- \captionsetup[table]{labelformat=nospace}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
library(bookdown)
```
\def\figurename{Figure A}
\def\tablename{Table A}
See Table A\#ref(tab:cars) for something about cars.
(ref:cars) Table caption
```{r cars}
kable(mtcars[1:5, ], booktabs=TRUE, caption="(ref:cars)") %>%
kable_styling(latex_options="hold_position", position="left")
```
Answer inspired by: Figure name in caption using RMarkdown
Caption latex package documentation: https://ctan.org/pkg/caption

How to embed highcharter in rmarkdown to share (not a loop)

I cannot get two simple highcharter charts in an Rmarkdown file I want to share. It works fine and renders in my PC or Mac, but when I share the file, people only see text.
They are not part of a loop, as mentioned in few articles. They are just two charts. For the reproducible example, I literally just opened a new rmarkdown doc and selected html. I replaced the "summary table" of cars with highcharter code. I even tried htmltools::tagList(chart1, chart2) and it does not work.
I am supplying the code. If you please show me how to do it with one chart, I can do it with the second.
Thank you.
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```{r echo=FALSE}
library(magrittr)
library(highcharter)
highchart() %>%
hc_add_series(cars, type = "scatter", hcaes(speed, dist))
I apologize if the tick marks hide the code background, but the three chunks are wrapped with the three tickmarks at the beginning and end of each chunk.
Thank you again.
Yes the code below produces the file below the code. I now have an entire .html file that has the highchart self contained in the file.
---
output:
html_document:
self_contained: yes
mode: selfcontained
---
{r echo=FALSE}
library(magrittr)
library(highcharter)
highchart() %>%
hc_add_series(cars, type = "scatter", hcaes(speed, dist))