savehistory not working properly in R?
Prof Brian Ripley wrote:
On Wed, 14 May 2003, Paul Y. Peng wrote:
I have a .RData which contains .Last object as follows:
.Last <- function ()
{
savehistory(file = ".Rhistory")
}
In this directory, if I issue the following command
Rterm --save < mycmds.q
to execute commands in mycmds.q and to save results in .RData,
I got the following error message towards the end of the execution:
Error in savehistory(file) : savehistory can only be used
in Rgui and Rterm
Execution halted
I lost the results of the commands too. The documentation of
"savehistory" says that it only works with Rgui and Rterm. Why
doesn't it work in this case? Is it because it is in a batch mode
rather than in an interactive mode?
Yes. The history is associated with the command-line editing: what you are doing is considered to be BATCH use.
Is it possible to prevent savehistory from printing the error message so that the session can be finished properly? I hope that I did not miss anything obvious. Otherwise, please forgive me. Thanks.
The real problem is in your .Last. You could do
.Last <- function ()
{
if(interactive()) savehistory(file = ".Rhistory")
}
Many thanks. As always, your suggestion works. I should have thought about interactive().
or use try(): if you are worried about not saving .RData you really should protect the commands in .Last (see its help page for warnings).
I will give try() a real try. It seems to be quite useful.
I'll see if the documentation can be clarified.
Why does R save its command history only when one saves the data image of the session? Is this a feature? Even though .Last can do this, would it be more convenient if R can do this automatically? Logically, I feel the command history should be treated separately. Paul.