Saving and loading history automatically

I use R software for statistical analysis, and I am sad that it does not save or restore my current command history. Indeed, pressing the up arrow on a recently launched interactive session R will each time show an empty history. It would be great if it could do it in a way, say, similar to ipython . I tried putting this in my .Rprofile file .Rprofile no avail. A file containing my command history is never 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 happens via SSH on a remote Linux server. Any help is much appreciated!

+4
source share
5 answers

In my ~/.profile , I have:

 export R_HISTFILE=~/.Rhistory 

In my ~/.Rprofile I have:

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

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

+7
source

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

0
source

You can consider emacs and ESS, which work great on SSH and allow you to use the more common (and usually more powerful) method of storing useful commands in a separate file.

0
source

An alternative to setting .Last is to register a finalizer for .GlobalEnv , which will be launched even if the R session is terminated 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 several additional bells here:

  • invisible() ensures that the return value of reg.finalizer() not printed when R starts
  • Unlike Hadley's answer, the .Rhistory file .Rhistory saved in the current directory. eval(bquote(... .(getwd()) ...)) evaluates getwd() at startup, so the directory current at startup is used on output
  • Setting onexit = TRUE ensures that the code is actually running
0
source

I would recommend you check out the Rstudio IDE here . It stores your story in a tab, if you ever want to view it, and when you end the session, it will ask you to ask if you want to save it for a subsequent session.

-1
source

Source: https://habr.com/ru/post/1482561/


All Articles