abraham
abraham

Reputation: 743

how to keep always Rhistory file in home?

I'm so sorry for this question, but I cant find the way to solve my problem.

I want to save my .Rhistory always in a specific place, specifically in home directory (~/.Rhistory), even if a save my .RData in a different folder ( ~/Desktop/R_working_directory).

I'm using a macOS, in this sense if I going to close Rstudio, I have to change to home ( setwd("~/") ) and then close it to save my history in home, but some times I just forget to change to home directory, and then I have different .Rhistory files; I want to keep all the history in the same folder (something like shell/bash that always keep the history file in home: ~/.bash_history, even if the working directory is different !!).

Thanks so much

Upvotes: 1

Views: 2030

Answers (3)

UgurAle
UgurAle

Reputation: 1

  1. Set the R_HISTFILE environment variable to ~/.Rhistory to make R look for it there to restore from it. You can do that by adding the following line to ~/.Renviron[2], which contains user-defined environment variables:
   R_HISTFILE="~/.Rhistory"
  1. Tell R to also save the history to this file on exit. For this, you can use the .Last() command, which "is (normally) executed at the very end of the session". This function should be defined inside ~/.Rprofile[3], where your user-level configurations of R reside:
    .Last <- function() {
        if(interactive()) try(savehistory("~/.Rhistory"))
    }

Together, this should ensure that your history is stored in as well as restored from one single file. See this chapter in R documentation for more information.

Keep in mind, however, that should you create .Renviron and/or .Rprofile in your project folder, these will override your user-level settings. To prevent that, import your user-level settings into your project explicitly by adding the following lines into your project's .Rprofile:

    readEnviron("~/.Renviron") # adds your user-level `.Renviron`
    source("~/.Rprofile")      # adds your user-level `.Rprofile`

See help("Startup") in R for more information.


[2]: This file's location can actually be controlled by using another environment variable, R_ENVIRON_USER

[3]: dito, but with R_PROFILE_USER


Edit: In Step 2, added the check for an interactive session (basically, whether R was opened by you or as part of some script) as recommended by R - see help("savehistory")

Upvotes: 0

Jan
Jan

Reputation: 5254

You could explicitely save it with savehistory(file = "mypath/wherever/today.Rhistory").

Upvotes: 0

Suresh_Patel
Suresh_Patel

Reputation: 311

I might be wrong but I think R will always save .Rhistory in your working directory.

Upvotes: 2

Related Questions