Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving and loading history automatically

Tags:

r

profile

history

I'm using the R software for statistical analysis and am sad that it doesn't preserve and restore my prompt command history. Indeed, pressing the up arrow on a newly started interactive R session will reveal a blank history, every time. It would be great if it could do this in manner, say, similar to ipython. I tried putting this in my .Rprofile file to no avail. No file containing my command history is ever created.

.First <- function(){
        if (!any(commandArgs()=='--no-readline') && interactive()){
                require(utils)
                try(loadhistory(Sys.getenv("R_HISTFILE")))
        }
}

.Last <- function() {
        if (!any(commandArgs()=='--no-readline') && interactive()){
                require(utils)
                try(savehistory(Sys.getenv("R_HISTFILE")))
        }
}

Of course this line is present in my .bash_profile

export R_HISTFILE="$HOME/share/r_libs/.history"

All this is happening via SSH on a remote server running Linux. Any help greatly appreciated !

like image 705
xApple Avatar asked May 24 '13 12:05

xApple


2 Answers

In my ~/.profile I have:

export R_HISTFILE=~/.Rhistory

In my ~/.Rprofile I have:

if (interactive()) {
  .Last <- function() try(savehistory("~/.Rhistory"))
}

and that works for me (although it doesn't work very well if you have multiple R sessions open)

like image 86
hadley Avatar answered Sep 23 '22 07:09

hadley


An alternative to setting .Last is registering a finalizer for .GlobalEnv, which will be run even if the R session is exited with EOF (Ctrl+Z on Windows and Ctrl+D elsewhere):

if (interactive()) {
  invisible(
    reg.finalizer(
      .GlobalEnv,
      eval(bquote(function(e) try(savehistory(file.path(.(getwd()), ".Rhistory"))))),
      onexit = TRUE))
}

There are some extra bells and whistles here:

  • invisible() makes sure the return value of reg.finalizer() isn't printed when R starts up
  • Contrary to Hadley's answer, the .Rhistory file is saved in the current directory. eval(bquote(... .(getwd()) ...)) evaluates getwd() during startup, so that the directory that is current during startup is used at exit
  • Setting onexit = TRUE makes sure that the code is actually run
like image 22
krlmlr Avatar answered Sep 20 '22 07:09

krlmlr