Clean last error in R - r

I would like to clean my current R session from the last error so that a next call to geterrmessage() will be empty.
Example:
> stop('halt !')
Error: halt !
> geterrmessage()
[1] "Error: halt !\n"
> something_that_cleans_the_last_error
> geterrmessage()
[1] ""
Thanks

Since there doesn't seem to be an easy to way to do this, here are some alternatives:
Start a new instance of R and quit the old one:
system("R"); q("no")
This will clear your workspace entirely. If you want to save your workspace, try:
save.image(); system("R"); q("no")
This restores your workspace, but will leave a lingering workspace file .Rdata. If you want to remove that as well:
save.image(); system("R"); unlink('.Rdata'); q("no");
But you will still have to reload any packages that you had previously loaded. That is, unless you do:
lp<-(.packages()); save.image(); system("R"); unlink('.Rdata'); q("no");
rapply(as.list(lp), library); rm(lp)
which only works from the command line, since the second line has to be entered into the new R shell.
Note: I don't actually recommend this solution.

Related

How to stop R from stopping execution on error?

I'm having an issue where if I execute several lines of code at once and one of them has an error, the lines below don't get executed.
For example if I have:
table(data$AGE)
table(dataREGION)
table(date$SEXE)
I get the table for the first line, and then
Error in table(dataREGION) : object 'dataREGION' not found
>
And the last line does not execute.
Does anyone know why it does that and how to fix it?
(I work with R 4.2.2 and RStudio 2022.12.0+353 "Elsbeth Geranium" Release)
Thanks!
Have a nice day,
Cassandra
Fixed: In Global Options > Console, under "Execution" uncheck the "Discard pending console input on error"
It seems like you want to use try().
try(table(data$AGE), silent = F, outFile = T)
try(table(dataREGION)) # also works without any params
try(table(date$SEXE))
You can also use tryCatch() if you want more control but it doesn't seem necessary for your purpose.
__
As for why your dataREGION doesn't exectue:
Hazarding a guess it might be because you forgot the $ between data and REGION

Calling stop( ) within function causes R CMD Check to throw error

I am attempting to call stop( ) from within an internal package function (stop_quietly()) which should break the function and return to the topline. This works except that R CMD Check thinks this is an error because I am forcing stop.
How do I get around the R CMD check interpreting this as an error? The function needs to stop since it requires user input as a confirmation before it creates a file directory tree at a given location. The code currently produces a message and stops the function.
tryCatch({
path=normalizePath(path=where, winslash = "\\", mustWork = TRUE)
message(paste0("This will create research directories in the following directory: \n",path))
confirm=readline(prompt="Please confirm [y/n]:")
if(tolower(stringr::str_trim(confirm)) %in% c("y","yes","yes.","yes!","yes?")){
.....
dir.create(path, ... [directories])
.....
}
message("There, I did some work, now you do some work.")
}
else{
message("Okay, fine then. Don't do your research. See if I care.")
stop_quietly()
}
},error=function(e){message("This path does not work, please enter an appropriate path \n or set the working directory with setwd() and null the where parameter.")})
stop_quietly is an exit function I took from this post with the modification of error=NULL which suppresses R executing the error handler as a Browser. I do not want the function to terminate to a Browser I just want it to quit without throwing an error in the R CMD Check.
stop_quietly <- function() {
opt <- options(show.error.messages = FALSE, error=NULL)
on.exit(options(opt))
stop()
}
Here is the component of the error R CMD produces:
-- R CMD check results ------------------------------------------------ ResearchDirectoR 1.0.0 ----
Duration: 12.6s
> checking examples ... ERROR
Running examples in 'ResearchDirectoR-Ex.R' failed
The error most likely occurred in:
> base::assign(".ptime", proc.time(), pos = "CheckExEnv")
> ### Name: create_directories
> ### Title: Creates research directories
> ### Aliases: create_directories
>
> ### ** Examples
>
> create_directories()
This will create research directories in your current working directory:
C:/Users/Karnner/AppData/Local/Temp/RtmpUfqXvY/ResearchDirectoR.Rcheck
Please confirm [y/n]:
Okay, fine then. Don't do your research. See if I care.
Execution halted
Since your function has global side effects, I think check isn't going to like it. It would be different if you required the user to put tryCatch at the top level, and then let it catch the error. But think about this scenario: a user defines f() and calls it:
f <- function() {
call_your_function()
do_something_essential()
}
f()
If your function silently caused it to skip the second line of f(), it could cause a lot of trouble for the user.
What you could do is tell the user to wrap the call to your function in tryCatch(), and have it catch the error:
f <- function() {
tryCatch(call_your_function(), error = function(e) ...)
do_something_essential()
}
f()
This way the user will know that your function failed, and can decide whether or not to continue.
From discussion in the comments and your edit to the question, it seems like your function is only intended to be used interactively, so the above scenario isn't an issue. In that case, you can avoid the R CMD check problems by skipping the example unless it is being run interactively. This is fairly easy: in the help page for a function like create_directories(), set up your example as
if (interactive()) {
create_directories()
# other stuff if you want
}
The checks are run with interactive() returning FALSE, so this will stop the error from ever happening in the check. You could also use tryCatch within create_directories() to catch the error coming up from below if that makes more sense in your package.

.Last() in .RProfile doesn't execute

I'm trying to make R restart on quit, so I'm using .Last in my .Rprofile.
Solution modified from Quit and restart a clean R session from within R?, and I've tried the other solutions in that answer to no avail.
my .First() works fine, but when I q() at the end, it prompts for "save workspace image?" and after answering, it insta-closes
.Last <- function()
{
print("new R in 3 seconds")
Sys.sleep(3)
system("R --no-save")
print("close R in 3 seconds")
Sys.sleep(3)
}
print("test")
(the print at the end is because there's a hidden "feature" where .Rprofile ignores the last line if theres no newline, I know it shouldn't execute that.)

getting the name of a dataframe from loading a .rda file in R

I am trying to load an .rda file in r which was a saved dataframe. I do not remember the name of it though.
I have tried
a<-load("al.rda")
which then does not let me do anything with a. I get the error
Error:object 'a' not found
I have also tried to use the = sign.
How do I load this .rda file so I can use it?
I restared R with load("al.rda) and I know get the following error
Error: C stack usage is too close to the limit
Use 'attach' and then 'ls' with a name argument. Something like:
attach("al.rda")
ls("file:al.rda")
The data file is now on your search path in position 2, most likely. Do:
search()
ls(pos=2)
for enlightenment. Typing the name of any object saved in al.rda will now get it, unless you have something in search path position 1, but R will probably warn you with some message about a thing masking another thing if there is.
However I now suspect you've saved nothing in your RData file. Two reasons:
You say you don't get an error message
load says there's nothing loaded
I can duplicate this situation. If you do save(file="foo.RData") then you'll get an empty RData file - what you probably meant to do was save.image(file="foo.RData") which saves all your objects.
How big is this .rda file of yours? If its under 100 bytes (my empty RData files are 42 bytes long) then I suspect that's what's happened.
I had to reinstall R...somehow it was corrupt. The simple command which I expected of
load("al.rda")
finally worked.
I had a similar issue, and it was solved without reinstall R. for example doing
load("al.rda) works fine, however if you do
a <- load("al.rda") will not work.
The load function does return the list of variables that it loaded. I suspect you actually get an error when you load "al.rda". What exactly does R output when you load?
Example of how it should work:
d <- data.frame(a=11:13, b=letters[1:3])
save(d, file='foo.rda')
a <- load('foo.rda')
a # prints "d"
Just to be sure, check that the load function you actually call is the original one:
find("load") # should print "package:base"
EDIT Since you now get an error when you load the file, it is probably corrupt in some way. Try this and say what it prints:
file.info("a1.rda") # Prints the file size etc...
readBin("a1.rda", "raw", 50) # reads first 50 bytes from the file
Without having access to the file, it's hard to investigate more... Maybe you could share the file somehow (http://www.filedropper.com or similar)?
I usually use save to save only a single object, and I then use the following utility method to retrieve that object into a given variable name using load, but into a temporary namespace to avoid overwriting existing objects. Maybe it will be helpful for others as well:
load_first_object <- function(fname){
e <- new.env(parent = parent.frame())
load(fname, e)
return(e[[ls(e)[1]]])
}
The method can of course be extended to also return named objects and lists of objects, but this simple version is for me the most useful.

How to preserve changes to function with fix() between R sessions?

If I edit a function with R v2.14.0 using fix(), those fixes are applied during the session.
For example, I might make the following edit to get a white background in a hive plot:
> library(HiveR)
> fix(plotHive)
... :%s/black/white/g
... :w
... :q
> plotHive(myHiveData)
I then get a white background in the hive plot, as expected.
But if I quit and reopen R, I have lost those changes, and the plot has a black background again.
How do I preserve the edits I make with fix() between R sessions?
EDIT
If I source() the modified plotHive() function, I get the following error:
> modifiedPlotHive <- source("modifiedPlotHive.R")
Error in source("modifiedPlotHive.R") :
modifiedPlotHive.R:1160:1: unexpected '<'
1159: }
1160: <
^
In addition: Warning message:
In readLines(file) : incomplete final line found on 'modifiedPlotHive.R'
The final line in the modified plotHive() function is:
<environment: namespace:HiveR>
If I remove this line before source()-ing, then the function no longer works.
Sorry I missed this when it came out, but the latest version of HiveR has the option to control the background color (available on CRAN 0.2-1) Bryan
Here's the safer way of doing what you want, referenced by #joran.
The sink/source pair is fine for dealing with R code files. But saving to text files and then reading back in other types of objects can strip them of important attributes, especially those relating to environments. That's what you just experienced.
The save/load pair stores objects in R's own binary format, so is much less liable to lose important information/environments attached to functions.
In this example, I define a personal version of ls, which differs from the base function in that it by default lists objects that start with a dot/period:
my_ls <- ls
fix(my_ls)
# 1) On the first line, change 'all.names=FALSE' to 'all.names=TRUE'
# 2) Say "Yes", I want to save the changes
save("my_ls", file="my_ls.Rdata")
# Then, in a later session, test that it works
load("my_ls.Rdata")
.TrysToHide <- 99
my_ls()
# [1] ".TrysToHide" "my_ls"
One more note: it's much cleaner to give your modified function a name of its own. To really edit a packaged function, and have the changes persist, you'd need to edit the sources and recompile the package. But if you do that, beware, as you may well break the function for other packaged functions that depend on it.
There are a couple of options:
Save your workspace before quiting and load it again when you reopen R.
Save the modified function to script file and source it:
sink("modified_plotHive.r")
plotHive
sink()
In the next session:
plotHive <- source("modified_plotHive.r")
HTH

Resources