cross-reference within the code chunk in Rmarkdown

Hi all, I am creating a Word document and want to do the cross-reference to a figure.

There is a condition to show Or not show the plot.

In case, the plot can be shown, I can do @ref(fig:fig1). When the plot is not shown, then I do not need to have the cross-reference.

Is there any way to automate this based on a condition? like an "ifelse" function within the code chunk?

Many thanks.

Hi @ChloeCao

you will need bookdown since rmarkdown doesn't support cross references out of the box.

---
title: '186960'
author: "ChloeCao"
date: "2024-05-20"
output: 
  bookdown::word_document2
---

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

## Code containing condition

Some text ...

```{r condition}
temp <- TRUE
```

## Including Plots

You can also embed plots `r ifelse(temp, "for example \\@ref(fig:pressure) shown below.", "but you said temp is false so i will not produce anything.")`

```{r pressure, eval=temp, echo=temp, fig.cap="Pressure"}
plot(pressure)
```
1 Like

Thank you @vedoa. I have added "\" in front of @ref(fig:fig1) within the "if-else" function. And it works.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

You can also use Quarto now which brings these types of features for all formats .