Change default prompt and output line prefix in R?

Viewed 7030

For the purposes of teaching and preparing written instructions about R, one of the things that's always frustrated me is that I can't simply copy commands and output from R and paste them into another R session. For example, if I do something trivial, such as

> x <- rnorm(10)
> x
 [1]  1.76975998  1.19722850 -0.39274507 -1.10979974  0.52320473 -0.08643833
 [7]  0.94437690  0.08083207  0.62260363  1.89305469

If I copy and paste that into a document or even here in this post, you (and my students) can not then just highlight it, copy it and paste it into an R session successfully

> > x <- rnorm(10)
Error: syntax error
> > x
Error: syntax error
>  [1]  1.76975998  1.19722850 -0.39274507 -1.10979974  0.52320473 -0.08643833
Error: syntax error
>  [7]  0.94437690  0.08083207  0.62260363  1.89305469
Error: syntax error

You might want to do this to test your installation of R, compare my output to yours, or simply to make use of a function I've offered.

So, what I'd like to be able to do is to change the default prompt from > to either an empty string or a blank space and also prefix all output lines with a hash mark #. That way, I could use R interactively to generate a session that looks like

x <- rnorm(10)
x
# [1]  1.76975998  1.19722850 -0.39274507 -1.10979974  0.52320473 -0.08643833
# [7]  0.94437690  0.08083207  0.62260363  1.89305469

which could be copy/pasted into an R session successfully. It would make prepping R code for a journal article, students, lectures, etc. much easier for me (and maybe for others?)

I've poked around the documentation with no luck... any ideas? pointers?

Currently, I'm using R on a Mac either via the R.app GUI or from Terminal.

11 Answers

Coming in very late to the game, just pointing out that almost anything desired can be put into a prompt. Homage to many unix programmers' shell prompt:

options(prompt = paste0(getwd(),'\n> '))

Probably a way to toss colors in there too.

Similar to the chosen answer this has been put into an RStudio Addin called mischelper (https://github.com/dracodoc/mischelper) where one of its functions does this exactly. The benefit of having it as an Addin is that you can turn it into a keyboard shortcut which I think is missing from the other solutions posted here. Usually paste is Ctrl + V so I have script/code I wanted copied in from the console as Ctrl + B. It pastes:

> x <- rnorm(10)
> x
 [1] -1.5337  0.7866  0.2721 -1.9644  0.0648  1.1001 -0.1761 -0.9213 -1.5025  1.3947

as:

x <- rnorm(10)
x
#  [1] -1.5337  0.7866  0.2721 -1.9644  0.0648  1.1001 -0.1761 -0.9213 -1.5025  1.3947

Might be helpful to someone....

Related