xApple
xApple

Reputation: 6466

Saving and loading history automatically

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 !

Upvotes: 9

Views: 2887

Answers (4)

krlmlr
krlmlr

Reputation: 25454

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

Upvotes: 1

Aaron - mostly inactive
Aaron - mostly inactive

Reputation: 37754

You might consider emacs and ESS, which work fine over SSH and allow for the more usual (and generally considered more powerful) method of keeping useful commands in a separate file.

Upvotes: 0

hadley
hadley

Reputation: 103898

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)

Upvotes: 15

odessa
odessa

Reputation: 98

If you work with Rgui : savehistory(), loadhistory() and history() could do the job. Otherwise I guess it depends on the IDE..

Upvotes: 0

Related Questions