Zoë Clark Zoë Clark - 3 months ago 18
R Question

Changing the prompt in a multilanguage knitr/RMarkdown document

I'm writing a

.Rmd
file that displays both bash commands and R commands. Is there a way to differentiate the chunks with R code from those with bash code? There's a knitr chunk option that inserts the R command prompt into a chunk so that

```{R, prompt = "true"}
plot(rnorm(100))
```


becomes

> plot(rnorm(100))


but for the bash chunks this

```{bash, prompt = "true"}
pandoc --version
```


becomes this

> pandoc --version


when I would prefer this

$ pandoc --version

Answer

You could try a simple hook:

---
output: html_document
---

```{r}
library('knitr')
knit_hooks$set(
  prompt = function(before, options, envir) {
    options(prompt = if (options$engine %in% c('sh','bash')) '$ ' else 'R> ')
})
```

```{r, prompt=TRUE}
1+1
```

but for the bash chunks this

```{bash, prompt=TRUE}
pandoc --version | head -1
```

```{r, prompt=TRUE}
1+1
```

enter image description here

And you can add opts_chunk$set(prompt=TRUE) so you don't have to keep writing prompt=TRUE for every chunk