Conditionally Display a Block of Text in R Markdown

Conditionally display a block of text in R Markdown

You need a complete R expression, so you cannot break it into multiple blocks like you show, but if the results of a block are a text string then it will be included as is (without quotes), so you should be able to do something like:

`r if(show.text){"la la la"}`

and it will include the text if and only if show.text is TRUE.

Conditionally display block of markdown text using knitr

You could use the asis engine to conditionally include/exclude arbitrary text in knitr, e.g.

```{asis, echo=FALSE}
Some arbitrary text.

1. item
2. item

Change echo=TRUE or FALSE to display/hide this chunk.
```

But I just discovered a bug in this engine and fixed it. Unless you use knitr >= 1.11.6, you can create a simple asis engine by yourself, e.g.

```{r setup, include=FALSE}
library(knitr)
knit_engines$set(asis = function(options) {
if (options$echo && options$eval) paste(options$code, collapse = '\n')
})
```

If you want to include inline R expressions in the text, you will have to knit the text, e.g.

```{r setup, include=FALSE}
library(knitr)
knit_engines$set(asis = function(options) {
if (options$echo && options$eval) knit_child(text = options$code)
})
```

Conditionally display block of text with code inside string section

Using paste you could do:

Also note that there was a bug in your condition which I fixed.

---
title: "Untitled"
output: html_document
date: '2022-07-22'
---

```{r}
df <- data.frame(
column = 1:2
)
```

`r if (nrow( subset(df,column == 1)) != 0) paste("Multiple choice variable with", nrow(subset(df, column == 1)), "missing values.") else ""`

Sample Image

Conditionally display markup formatted text based on shiny input

The the following in your Rmd file. You already are in a code block and don't need to have additional inline r formatting. You can use results = 'asis' in your block and also add the header (#) for identical formatting if you'd like:

```{r, echo=FALSE, results='asis'}
if(BoxValue == TRUE){
cat("# Value for input 2 is", Input2Value)
}
```

Is there a way to have conditional markdown chunk execution in Rmarkdown?

Instead of using cat to print the solution from within an R code chunk, you could write the solution as you usually would in rmarkdown (i.e., with the usual combination of text, latex, and R code chunks), and use the parameter soln to comment out that section when you don't want to include the solution in the final document.

In the sample rmarkdown document below, if the parameter soln is FALSE, then the line r if(!params$soln) {"\\begin{comment}"} inserts \begin{comment} to comment out the solution (with matching code at the end to insert \end{comment}). I've also indented everything with two tabs, so that the question numbers are formatted with a hanging-indent. (If you like this format, you don't have to type the double-tab for each new paragraph or chunk. If you do this for one line, then each subsequent time you press the Enter key, the new line will automatically be formatted with the double-tab. Or, just type in all your text and code for a given question, then when you're done, highlight all of it and type tab twice.)

---
title: "Homework"
output: word_document
header-includes:
- \usepackage{comment}
params:
soln: TRUE
---

1. Fit the linear regression model $Y \sim X$ with the following data. Interpret the coefficient estimates.

```{r promptchunk, echo = TRUE}
set.seed(123)
X <- c(1, 1, 0, 0)
Y <- rnorm(4)
```

`r if(!params$soln) {"\\begin{comment}"}`

**Solution:**

Run the following R code to fit the linear regression model:
```{r, include = params$soln, echo = TRUE, results = "asis"}
fit1 = lm(Y ~ X)
```

To see a summary of the regression results, run the following code and review the output:

```{r, include = params$soln, echo=TRUE}
summary(fit1)
```
The interpretation of the intercept is....

Our estimate $\hat{\beta}_0$ is `r round(coef(fit1)[1], 2)`.

The estimated X coefficient $\hat{\beta}_1$ is `r round(coef(fit1)[2], 2)`.

This can be interpreted as....

`r if(!params$soln) {"\\end{comment}"}`

Also, instead of knitting the file above interactively, you can render both versions by running the render function in a separate R script. For example, assuming the file above is called hw.Rmd, open a separate R script file and run the following:

for (i in c(TRUE, FALSE)) {
rmarkdown::render("hw.Rmd",
params = list(soln = i),
output_file=ifelse(i, "Solutions.doc", "Homework.doc"))
}

Below is what Solutions.doc looks like. Homework.doc is similar, except everything from the bold word Solution: onward is excluded:

Sample Image

Conditional text in RMarkdown using multiple variables

You can use any kind of conditional logic within the chunk option. If you have more than one condition which needs to be met, you can use the & symbol between them which will require both to be TRUE. Here is a basic example:

a<-6
b<-3
c<-2

a>b & a>c

TRUE

# Make a less than c but bigger than b
a <- 2.5
a>b & a>c

FALSE

If you want to find out more about the use of operators in R, I recommend this page: https://www.statmethods.net/management/operators.html

Conditional title heading depending on output of code block R Markdown

I made minimal changes to implement your code with the iris dataset and it works as you would like it to.

No rows (and no header)

```{r warning = FALSE, echo = FALSE, fig.height=10, fig.width=6}
library(dplyr)
library(kableExtra)

#Existing data frame my_df
my_df <- iris[NULL, ]
numRows <- nrow(my_df)
```

`r if (numRows > 0) {"## This is your heading written in markdown"}`

```{r warning = FALSE, echo = FALSE, fig.height=10, fig.width=6}
if (numRows>0) {
#Print table
my_df %>%
arrange(Species) %>%
kable() %>%
kable_styling(bootstrap_options = "striped","condensed", font_size = 12)
}
```

With data (and table header)

```{r warning = FALSE, echo = FALSE, fig.height=10, fig.width=6}
library(dplyr)
library(kableExtra)

#Existing data frame my_df
my_df <- iris[1:10, ]
numRows <- nrow(my_df)
```

`r if (numRows > 0) {"## This is your heading written in markdown"}`

```{r warning = FALSE, echo = FALSE, fig.height=10, fig.width=6}
if (numRows>0) {
#Print table
my_df %>%
arrange(Species) %>%
kable() %>%
kable_styling(bootstrap_options = "striped","condensed", font_size = 12)
}
```


Related Topics



Leave a reply



Submit