balin
balin

Reputation: 1686

rmarkdown: recursive chunk evaluation?

I would like to have a string produced by an R chunk in an rmarkdown document to be re-evaluated - is that possible? For demonstration purposes consider the following document:

---
params:
  B: 'test'
---

```{r simple, results='asis', echo=FALSE}
write(params[['B']], file = "")
```

```{r recursive-evaluation-questionmark, results='asis', echo=FALSE}
write(
  "How to get \"params[['B']]\" evaluated here? This \"`r params[['B']]`\" is
    expected to be \"test\" ...",
  file = "")
```

Currently this produces the following when knitted:

test

How to get “params[[‘B’]]” evaluated here? This “r params[['B']]” is expected to be “test” …

but I want:

test

How to get “params[[‘B’]]” evaluated here? This “test” is expected to be “test” …

Upvotes: 0

Views: 191

Answers (1)

user2554330
user2554330

Reputation: 44788

You can't get knitr to treat R code as text, but you can solve the problem using pure R code. I'd also recommend using cat() instead of write(). For your example,

write(
  paste0("How to get \"params[['B']]\" evaluated here? This \"", params[['B']], "\" is
  expected to be \"test\" ..."),
 file = "")

or the simpler

cat("How to get \"params[['B']]\" evaluated here? This \"", params[['B']], "\" is
  expected to be \"test\" ...", sep = "")

For more complicated macro-like substitutions, you may want to use the sub() or gsub() functions, e.g.

msg <- "How to get \"params[['B']]\" evaluated here? This \"%param%\" is
  expected to be \"test\" ..."
cat(sub("%param%", params[['B']], msg))

Upvotes: 2

Related Questions