1

Is it possible to have entire sections programmatically commented out in RMarkdown. For example, say I have a section of my report :

### 2.1.   Heading

Blah blah blah my description, with `r variables` and other stuff.


#### Table 2.1.1. Sub heading

```{r table_2_1_1}

kable_2_1_1

```

Now based on a boolean in the code, I want to completely comment out that whole section. I've tried putting r variables into the report like "< !--" & "-->" but that does not work.

monkey
  • 1,213
  • 2
  • 13
  • 35
  • So, are you saying that if for example, you returned a 0 in the Section 1 block to a given variable, that you would want to ideally comment out this section 2? – AndrewGB Dec 21 '21 at 19:30
  • 3
    This may be useful: [Conditionally display block of markdown text using knitr](https://stackoverflow.com/questions/32944715/conditionally-display-block-of-markdown-text-using-knitr). – PaulS Dec 21 '21 at 19:47

1 Answers1

1

You can pass a boolean value to eval in your rmd chunk to conditionally knit different blocks of rmarkdown code:

---
title: "Untitled"
author: "Matt"
date: "12/21/2021"
output: html_document
---

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

should_i_evaluate <- F
```

```{r header, eval = should_i_evaluate}
asis_output("# My Header")
```

```{asis, echo = should_i_evaluate}
 Blah blah blah my description, with `r names(mtcars[1:3])` and other stuff.
```

```{r cars, eval = should_i_evaluate}
summary(mtcars)
```

When should_i_evaluate is TRUE:

When should_i_evaluate is FALSE:

Matt
  • 7,255
  • 2
  • 12
  • 34
  • Nice. That's half way there. If there are further sections, is there a way to remove the text too. For example, the blah blah blah. – monkey Dec 21 '21 at 21:56
  • That's just the generic `yaml` that is part of my default settings - I'm sure yours would look different. At the very top of my answer, you can see `title: "Untitled"` and `author: "Matt"`. You'd just need to edit them to be `""` if you want it to be blank, or whatever other text you'd like. – Matt Dec 21 '21 at 21:58
  • Sorry, I realised that and quickly edited my comment. – monkey Dec 21 '21 at 21:59
  • No worries - I updated the solution where you would do nearly the same thing, but include the text in an `asis` block, and feed your boolean value to `echo` rather than `eval` – Matt Dec 21 '21 at 22:07
  • Any way to make this work for a heading? – monkey Dec 21 '21 at 22:19
  • 1
    Yes! Updated again - you need to include `library(knitr)` and add an `R` chunk using `asis_output()` – Matt Dec 21 '21 at 23:27
  • Yes! Works perfectly. Need to supply \n with the asis_output strings. – monkey Dec 22 '21 at 00:13