Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show working directory in R prompt? [duplicate]

I would like to see the current working directory in the prompt of my R console. When using options(prompt=paste(getwd(),">> ")) the working directory at the start of the session is shown. But it never gets updated when I change the working directory during that session:

/home/sieste >> setwd("newdir")
/home/sieste >> cat("damn!\n")

What I do at the moment is to redefine the setwd function in my .Rprofile

setwd <- function(...) {
  base::setwd(...)
  options(prompt=paste(getwd(),">> "))
}

Now the prompt gets updated correctly whenever I call setwd. My question is: Is there a more elegant way of updating the prompt dynamically, independent of which function I call and without having to redefine base functions?

like image 374
sieste Avatar asked Aug 05 '14 10:08

sieste


1 Answers

Because prompt option is really just a string, without any special directives evaluated inside (unlike shell prompt), you have to change it if you change working directory to get current working directory inside.

The solution you use seems the best to me. A bit hacky, but any solution will be as you want to implement something quite fundamental that is not supported by R itself.

Moreover, you don’t have to fear functions executing base::setwd under the hood, which would get your prompt out of sync with real working directory. That does not happen in practice. As Thomas pointed out in the comments, probably no base functions (other than source) call setwd. The only functions that do are related to package building and installation. And I noticed that even in source and usually in the other functions, setwd is used like owd <- setwd(dir); on.exit(setwd(owd)), so that the working directory is set back to original when the function finishes.

like image 171
Palec Avatar answered Sep 27 '22 19:09

Palec