7

I have a program in R. Sometimes when I save history, they do not write into my history file. I lost some histories a few times and this really drive me crazy.

Any recommendation on how to avoid this?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Lily
  • 637
  • 2
  • 7
  • 16

4 Answers4

8

First check your working directory (getwd()). savehistory() saves the history in the current working directory. And to be honest, you better specify the filename, as the default is .History. Say :

savehistory('C:/MyWorkingDir/MySession.RHistory')

which allows you to :

loadhistory('C:/MyWorkingDir/MySession.RHistory')

So the history is not lost, it's just in a place and under a name you weren't aware of. See also ?history.

To clarify : the history is no more than a text file containing all commands of that current session. So it's a nice log of what you've done, but I almost never use it. I construct my "analysis log" myself by using scripts, as hinted in another answer.

Joris Meys
  • 106,551
  • 31
  • 221
  • 263
  • The help file for history has a "must have" feature that automatically saves history via the .Last function stored in a .RProfile. I rely on this alot! – Jeff Apr 12 '11 at 14:07
  • Joris: I agree. It is better to use my own script editor. R's history panel washes down every command, whatever wrong or not. – Lily Apr 13 '11 at 13:51
1

@Stedy has provided a workable solution to your immediate question. I would encourage you to learn how to use .R files and a proper text editor, or use an integrated development environment (see this SO page for suggestions). You can then source() in your .R file so that you can consistently replicate your analysis.

For even better replicability, invest the time into learning Sweave. You'll be glad you did.

Community
  • 1
  • 1
Ari B. Friedman
  • 71,271
  • 35
  • 175
  • 235
1

Check the Rstudio_Desktop/history_database file - it stores every command for any working directory.

See here for more details How to save the whole sequence of commands from a specific day to a file?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
brucezepplin
  • 9,202
  • 26
  • 76
  • 129
  • 1
    This might be the most useful thing I've learned in the last 2 years. Thank you so much for this answer... Seriously just saved me days of work due to a RHistory file that wasn't updating. – quickreaction Aug 02 '22 at 19:13
0

Logging your console on a regular basis to **dated* files is handy. The package TeachingDemos has a great function for logging your console session, but it's written as a singleton, which is problematic for automatic logging, since you wouldn't be able to use that function to create teaching demo's if you use it for logging. I re-used that function using a bit of meta-programming to make a copy of that functionality that I include in the .First function in my local .Rprofile, as follows:

.Logger <- (function(){

    # copy local versions of the txtStart,
    locStart  <-  TeachingDemos::txtStart
    locStop  <-  TeachingDemos::txtStop
    locR2txt  <-  TeachingDemos:::R2txt

    # creat a local environment and link it to each function
    .e.  <-  new.env()
    .e.$R2txt.vars <- new.env()
    environment(locStart) <- .e.
    environment(locStop) <- .e.
    environment(locR2txt) <- .e.


    # reference the local functions in the calls to `addTaskCallback`
    # and `removeTaskCallback`
    body(locStart)[[length(body(locStart))-1]] <- 
        substitute(addTaskCallback(locR2txt, name='locR2txt'))
    body(locStop)[[2]] <- 
        substitute(removeTaskCallback('locR2txt'))


    list(start=function(logDir){
                op <- options()
                locStart(file.path(logDir,format(Sys.time(), "%Y_%m_%d_%H_%M_%S.txt")),
                         results=FALSE)
                options(op)
    }, stop = function(){
                op <- options()
                locStop()
                options(op)
    })

})()



.First <- function(){

    if( interactive() ){

        # JUST FOR FUN
        cat("\nWelcome",Sys.info()['login'],"at", date(), "\n")
        if('fortunes' %in% utils::installed.packages()[,1] )
            print(fortunes::fortune())

        # CONSTANTS
        TIME  <-  Sys.time()
        logDir  <- "~/temp/Rconsole.logfiles" 

        # CREATE THE TEMP DIRECORY IF IT DOES NOT ALREADY EXIST
        dir.create(logDir, showWarnings = FALSE)

        # DELETE FILES OLDER THAN A WEEK
        for(fname in list.files(logDir))
            if(difftime(TIME, 
                        file.info(file.path(logDir,fname))$mtime,
                        units="days") > 7 ) 
                file.remove(file.path(logDir,fname))

        # sink() A COPY OF THE TERMINAL OUTPUT TO A DATED LOG FILE
        if('TeachingDemos' %in% utils::installed.packages()[,1] )
            .Logger$start(logDir)
        else 
            cat('install package `TeachingDemos` to enable console logging')
    }

}

.Last  <-  function(){
    .Logger$stop()
}

This causes a copy of the terminal contents to be copied to a dated log file. The nice thing about having dated files is that if you use multiple R sessions the log files won't conflict, unless you start multiple interactive sessions in the same second).

Jthorpe
  • 9,756
  • 2
  • 49
  • 64