rmarkdown:递归块评估?

时间:2017-11-15 13:42:48

标签: r knitr r-markdown

我想在R文档中使用rmarkdown块生成的字符串进行重新评估 - 这可能吗?出于演示目的,请考虑以下文档:

---
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 = "")
```

目前在针织时产生以下效果:

test

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

但我想:

test

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

1 个答案:

答案 0 :(得分:2)

你无法让knitr将R代码视为文本,但您可以使用纯R代码解决问题。我还建议使用cat()代替write()。对于你的例子,

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

或更简单的

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

对于更复杂的类似宏的替换,您可能需要使用sub()gsub()函数,例如

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