I am looking to conditionally display a table in a rmarkdown document. Some of the tables that are generated by my code may contain empty cells and I'm looking to exclude those tables and replace them with a message. Something like:
if_else(is.na(table[3,1]) == TRUE,"Data is currently not available",knitr::kable(table))
Is this possible?
we create a TRUE/FALSE variable in a previous R chunk, then depending on a boolean operation, we get a value we can pass to the eval= R chunk options. In this example due to the result, we get a graph, instead of a table. Remember when naming R chunks, each one has to have a unique name.
---
title: "Untitled"
output: html_document
---
```{r setup, echo=FALSE, warning=FALSE, message=FALSE}
if (iris$Sepal.Length[[1]] > 5)
{show_text = TRUE
} else {show_text = FALSE}
```
```{r conditional_block, eval=show_text, echo=FALSE}
head(iris, 5)
```
```{r setup2, echo=FALSE, warning=FALSE, message=FALSE}
if (iris$Sepal.Length[[1]] < 5)
{show_text = TRUE
} else {show_text = FALSE}
```
```{r conditional_block2, eval=show_text, echo=FALSE}
plot(iris$Sepal.Length, iris$Sepal.Width)
```
Related
I have a parameterized RMarkdown file, parameterized.Rmd, with the following contents.
---
title: "Parameterized report"
output: html_document
params:
input_df: NULL
---
```{r sec1}
head(params$input_df[, 1:2])
```
I can knit it from the console using rmarkdown::render, generating distinct documents for distinct dataframe inputs. This works as expected.
rmarkdown::render("parameterized.Rmd",
params = list(input_df = mtcars),
output_file = "cars.html")
rmarkdown::render("parameterized.Rmd",
params = list(input_df = iris),
output_file = "iris.html")
I would like to have each of these results be child documents to a common document. My first attempt is with knitr::knit_child, but it does not take params as an argument. So this failed.
---
title: "Main report"
output: html_document
---
```{r test-cars}
knitr::knit_child("parameterized.Rmd", envir = environment(), quiet = T,
params = list(input_df = mtcars))
```
How may I knit together child documents which require parameters?
What worked for me (derived from the documentation once I properly understood it.):
Instead of using the params field in the YAML header, set the values of the parameters inside the main document and call cat on the output of knitr::knit_child. The below files achieved the desired result.
parameterized.Rmd
---
title: "Parameterized report"
output: html_document
---
```{r}
head(df[, 1:2])
```
main.Rmd
---
title: "Main report"
output: html_document
---
# mtcars
```{r mtcars, echo=FALSE, results='asis'}
df <- mtcars
cat(
knitr::knit_child('parameterized.Rmd', envir = environment(), quiet = TRUE)
)
```
# iris
```{r iris, echo=FALSE, results='asis'}
df <- iris
cat(
knitr::knit_child('parameterized.Rmd', envir = environment(), quiet = TRUE)
)
```
Knitting main.Rmd applied the parameterized report to each dataframe.
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
I am writing an article for a journal that requires Supplementary Material. I was hoping to use a unique label such as SuppMat: instead of the default fig: to send Figures and Tables into this section. If not, I can use the default fig label but I need numbering to restart in the Supplementary Material section of the document.
I am aware of one answer using latex (found here) but I must complete this when exporting to docx. Below is a reproducible example using officedown
---
output:
officedown::rdocx_document
---
```{r setup, include=FALSE}
pacman::p_load(knitr, officedown, officer)
knitr::opts_chunk$set(echo = FALSE,
eval = TRUE,
fig.cap = TRUE)
```
# Main Text
Please see Supplementary Figure \#ref(fig:appendix-fig1) and Figure \#ref(fig:main-fig1).
```{r fig.id="main-fig1", fig.cap="This should be labelled **Figure 1**"}
barplot(1:5, col=1:5)
```
```{r tab.id="main-tab1", tab.cap="Main Text Table 1"}
head(mtcars)
```
\newpage
# Supplementary Materials {#SuppMat}
```{r fig.id="appendix-fig1", fig.cap="This figure should be labelled **Supplementary Figure 1**"}
barplot(1:5, col=1:5)
```
```{r tab.id="appendix-tab1", tab.cap="Should be labelled **Supplementary Table 1**"}
head(mtcars)
```
After searching multiple forums and hours, I was able to come up with a solution using the officedown package. Hopefully this helps someone else out. For further details check out the run_autonum function.
---
output: officedown::rdocx_document
---
```{r setup, include=FALSE}
pacman::p_load(officedown, officer, knitr)
knitr::opts_chunk$set(echo = FALSE, fig.cap = TRUE)
ft_base <- fp_text(font.family = "Cambria", font.size = 12, bold = TRUE)
ft1 <- update(ft_base, shading.color='#EFEFEF', color = "red")
ft2 <- update(ft_base, color = "#C32900")
srcfile <- file.path( R.home("doc"), "html", "logo.jpg" )
extimg <- external_img(src = srcfile, height = 1.06/5, width = 1.39/5)
```
## References
This is a reference to an supplementary image caption whose number is Supplementary Figure \#ref(fig:faithfuld-plot) and \#ref(fig:supp-bar).
Testing another figure with a barplot in Figure \#ref(fig:plotbar)
```{r fig.id="plotbar", fig.cap = "Main Figure"}
barplot(1:8, col=1:2)
```
## Supplementary Material
```{r fig.id="faithfuld-plot"}
knitr::include_graphics("images/MyImage.png") # Use your own figure here (I needed to test with knitr for my workflow)
block_caption("First Appendix Figure",
style = "Figure",
autonum = run_autonum(seq_id = 'fig',
bkm = 'faithfuld-plot',
pre_label = "Supplemental Figure ",
start_at=1))
```
```{r fig.id="supp-bar"}
barplot(1:8, col=1:2)
block_caption("Second Appendix Figure",
style = "Figure",
autonum = run_autonum(seq_id = 'fig',
bkm = 'supp-bar',
pre_label = "Supplemental Figure ",
start_at= NULL))
```
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
I have a shiny app created with Rmd / Flexdashboard with many charts and tables. It is working well. Recently, I started using shiny_prerendered to improve the UX during startup. Now the page loads up faster but all the sections are empty (this is expected - the html renders but the charts and tables are still waiting for data) until the server code runs.
Is it possible to have some placeholder data during setup that will load the shiny output? Reactive outputs are not recognized in the setup context. Is this what the server-start context is for? I have tried too that without success?
Here is a simple code with a two value boxes
---
title: "ValueBoxTest"
output:
flexdashboard::flex_dashboard:
vertical_layout: fill
theme: united
runtime: shiny
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, options(scipen = 1, digits = 2))
### load packages
```
# ValueBox Test
===============================================
## Row 1
### Box 1
```{r, context="server"}
output$value1 <- renderValueBox({
### p <- 100 starting value placeholder
### call function to generate "p"
p <- functionToGenerateValue()
valueBox(p, icon = "fa-usd")
})
```
```{r echo = FALSE}
valueBoxOutput("value1")
```
## Row 2
### Box 2
```{r, context="server"}
output$value2 <- renderValueBox({
### q <- 0 starting value placeholder
### call function to generate "q"
q <- functionToGenerateValue()
valueBox(q, icon = "fa-usd")
})
```
```{r echo = FALSE}
valueBoxOutput("value2")
Well, it may be simpler than you might think. For example, why don't you try to change from runtime:shiny to runtime:shiny_prerendered? It may do the trick.