Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 883
Zoë Clark Avatar asked Aug 18 '16 16:08

Zoë Clark


1 Answers

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

like image 153
rawr Avatar answered Sep 24 '22 22:09

rawr