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 !
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)
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.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 exitonexit = TRUE makes sure that the code is actually run If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With