catching an exception on R getGEO - r

I am using R and the GEOQuery package for downloading a set of GEO profiles. For doing this I use the following instructions:
library(Biobase)
library(GEOquery)
gdsAcc<-getGEO('GDS1245',destdir=".")
which downloads the GDS1245.soft.gz in the specified directory.
The problem is that some GEO profiles have been removed, so when I use the above mentioned instructions in a loop and I came with something like:
gdsAcc<-getGEO('GDS450',destdir=".")
in the last case the profile GDS450 does not exist so it throws an error and the program stops. I would like to know how I can catch that error so that in case that the profile does not exist the program will continue looking for the other profiles.
My algorithm is something like:
for (i in 1:length_GEO_profiles){
disease<-GEOname
gdsName<-paste("GDS",disease,sep="")
gdsAcc<-getGEO(gdsName,destdir=".")
}
Any help?
Thanks

You should look at try and tryCatch. Here's an example to get you started:
for(i in 1:3) {
if(i == 1)
gdsAcc <- try(getGEO('GDS450',destdir="."))
cat(i, "\n")
}
If you want to do something with the error, then use an if statement:
if(class(gdsAcc) == "try-error") cat("HELP")
Related questions
Exception handling in R
Equivalent of "throw" in R
catching an error and then branching logic

Related

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.

Continuation Line error in R

This feels like a very simple question, but I can't find an answer anywhere I've searched. I'm new to R and when I try to break up my code across several lines with ctrl+shift+enter, but I don't get the '+' that should start the line in the console, and I get an error message when I try to run it. Sample code is:
for (j in 1:length(codes)) {
currCountry <- subset(currRegion, Country.Code == codes[j])
currCountry <- currCountry[order(currCountry$variable, decreasing=FALSE),]
lines(1960:2009, currCountry$value, col="#00200070", lwd=0.8)
}
I get the following error:
Error: unexpected input in "for (j in 1:length(codes)) {‚"
If I copy the same code from the online tutorial I'm doing, it works fine, but each line starts with a '+'. What can I do to get this?

How do I avoid halting the execution of a standalone r script that encounters an error?

I am running an optimization program I wrote in a multi-language framework. Because I rely on different languages to accomplish the task, everything must be standalone so it can be launched through a batch file. Everything has been going fine for 2-3 months, but I finally ran out of luck when one of the crucial parts of this process, executed through a standalone R script, encountered something new and gave me an error message. This error message makes everything screech to a halt despite my best efforts:
selMEM<-forward.sel(muskfreq, musk.MEM, adjR2thresh=adjR2)
Procedure stopped (adjR2thresh criteria) adjR2cum = 0.000000 with 0 variables (superior to -0.005810)
Error in forward.sel(muskfreq, musk.MEM, adjR2thresh = adjR2) :
No variables selected. Please change your parameters.
I know why I am getting this message: it is warning me that no variables are above the threshold I have programmed to retain during a forward selection. Although this didn't happen in hundreds of runs, it's not that big a deal, I just need to tell R what to do next. This is where I am lost. After an exhaustive search through several posts (such as here), it seams that try() and tryCatch() are the way to go. So I have tried the following:
selMEM<-try(forward.sel(muskfreq, musk.MEM, adjR2thresh=adjR2))
if(inherits(selMEM, "try-error")) {
max<-0
cumR2<-0
adjR2<-0
pvalue<-NA
} else {
max<-dim(selMEM)[1]
cumR2<-selMEM$R2Cum[max]
adjR2<-selMEM$AdjR2Cum[max]
pvalue<-selMEM$pval[max]
}
The code after the problematic line works perfectly if I execute it line by line in R, but when I execute it as a standalone script from the command prompt, I still get the same error message and my whole process screeches to a halt before it executes what follows.
Any suggestions on how to make this work?
Note this in the try help:
try is implemented using tryCatch; for programming, instead of
try(expr, silent = TRUE), something like tryCatch(expr, error =
function(e) e) (or other simple error handler functions) may be more
efficient and flexible.
Look to tryCatch, possibly:
selMEM <- tryCatch({
forward.sel(muskfreq, musk.MEM, adjR2thresh=adjR2)
}, error = function(e) {
message(e)
return(NULL)
})
if(is.null(selMEM)) {
max<-0
cumR2<-0
adjR2<-0
pvalue<-NA
} else {
max<-dim(selMEM)[1]
cumR2<-selMEM$R2Cum[max]
adjR2<-selMEM$AdjR2Cum[max]
pvalue<-selMEM$pval[max]
}
Have you tried setting the silent parameter to true in the Try function?
max<-0
cumR2<-0
adjR2<-0
pvalue<-NA
try({
selMEM <- forward.sel(muskfreq, musk.MEM, adjR2thresh=adjR2)
max<-dim(selMEM)[1]
cumR2<-selMEM$R2Cum[max]
adjR2<-selMEM$AdjR2Cum[max]
pvalue<-selMEM$pval[max]
}, silent=T)

tryCatch does not catch an error if called though RScript

I'm facing a strange issue in R.
Consider the following code (a really simplified version of the real code but still having the problem) :
library(timeSeries)
tryCatch(
{
specificWeekDay <- 2
currTs <- timeSeries(c(1,2),c('2012-01-01','2012-01-02'),
format='%Y-%m-%d',units='A')
# just 2 dates out of range
start <- time(currTs)[2]+100*24*3600
end <- time(currTs)[2]+110*24*3600
# this line returns an empty timeSeries
currTs <- window(currTs,start=start,end=end)
message("Up to now, everything is OK")
# this is the line with the uncatchable error
currTs[!(as.POSIXlt(time(currTs))$wday %in% specificWeekDay),] <- NA
message("I'm after the bugged line !")
},error=function(e){message(e)})
message("End")
When I run that code in RGui, I correctly get the following output:
Up to now, everything is OK
error in evaluating the argument 'i' in
selecting a method for function '[<-': Error in
as.POSIXlt.numeric(time(currTs)) : 'origin' must be supplied
End
Instead, when I run it through RScript (in windows) using the following line:
RScript.exe --vanilla "myscript.R"
I get this output:
Up to now, everything is OK
Execution interrupted
It seems like RScript crashes...
Any idea about the reason?
Is this a timeSeries package bug, or I'm doing something wrong ?
If the latter, what's the right way to be sure to catch all the errors ?
Thanks in advance.
EDIT :
Here's a smaller example reproducing the issue that doesn't use timeSeries package. To test it, just run it as described above:
library(methods)
# define a generic function
setGeneric("foo",
function(x, ...){standardGeneric("foo")})
# set a method for the generic function
setMethod("foo", signature("character"),
function(x) {x})
tryCatch(
{
foo("abc")
foo(notExisting)
},error=function(e)print(e))
It seems something related to generic method dispatching; when an argument of a method causes an error, the dispatcher cannot find the signature of the method and conseguently raises an exception that tryCatch function seems unable to handle when run through RScript.
Strangely, it doesn't happen for example with print(notExisting); in that case the exception is correctly handled.
Any idea about the reason and how to catch this kind of errors ?
Note:
I'm using R-2.14.2 on Windows 7
The issue is in the way the internal C code implementing S4 method dispatch tries to catch and handle some errors and how the non-interactive case is treated in this approach. A work-around should be in place in R-devel and R-patched soon.
Work-around now committed to R-devel and R-patched.
Information about tryCatch() [that the OP already knew and used but I didn't notice]
I think you are missing that your tryCatch() is not doing anything special with the error, hence you are raising an error in the normal fashion. In interactive use the error is thrown and handled in the usual fashion, but an error inside a script run in a non-interactive session (a la Rscript) will abort the running script.
tryCatch() is a complex function that allows the potential to trap and handle all sorts of events in R, not just errors. However by default it is set up to mimic the standard R error handling procedure; basically allow the error to be thrown and reported by R. If you want R to do anything other than the basic behaviour then you need to add a specific handler for the error:
> e <- simpleError("test error")
> tryCatch(foo, error = function(e) e,
+ finally = writeLines("There was a problem!"))
There was a problem!
<simpleError in doTryCatch(return(expr), name, parentenv, handler): object 'foo'
not found>
I suggest you read ?tryCatch in more detail to understand better what it does.
An alternative is to use try(). To modify your script I would just do:
# this is the line with the uncatchable error
tried <- try(currTs[!(as.POSIXlt(time(currTs))$wday %in% specificWeekDay),] <- NA,
silent = TRUE)
if(inherits(tried, "try-error")) {
writeLines("There was an error!")
} else {
writeLines("Everything worked fine!")
}
The key bit is to save the object returned from try() so you can test the class, and to have try() operate silently. Consider the difference:
> bar <- try(foo)
Error in try(foo) : object 'foo' not found
> bar <- try(foo, silent = TRUE)
> class(bar)
[1] "try-error"
Note that in the first call above, the error is caught and reported as a message. In the second, it is not reported. In both cases an object of class "try-error" is returned.
Internally, try() is written as a single call to tryCatch() which sets up a custom function for the error handler which reports the error as a message and sets up the returned object. You might wish to study the R code for try() as another example of using tryCatch().

To capture the warning thrown by the R script using R.NET

When I use the below script in R Console it gave me the output as string "Warning"
jj = ts(scan("jj.dat"), start=1960, frequency=4)
tryCatch(arima(jj,
order = c(1, 0,1)),
warning=function(w) cat("Warning"))
I tried to use the same code in R.NET and expected to get the string "Warning", but I'm getting Parser Exception showing "Code error". Below is the code snippet which I tried in R.NET.
try
{
string script = "tryCatch(arima(jj,
order = c(4, 0,6)),
warning=function(w) cat(\"Warning\"))";
string str=engine.EagerEvaluate("script").AsCharacter().First();//*
}catch (Exception ex)
{
}
Kindly throw to me some idea, on how can we tackle this issue. Or is there any other way to capture the R Script warnings and error messages in R.NET.
From my experience in these kind of R integration into other languages (rpy, coupling python and R) I would keep the amount of R source code inside .NET at a minimum. The way I would go would be to write a function inside a .R file which does what you want.
hello = function() { print("Hello World") }
Saving this function inside spam.r allows you to use source in order to load this new function into the R session running inside .NET. Then you can a very simple R script:
source("spam.r")
hello()
This is ofcourse a quite trivial example, but hello could contain much more complicated code. In this way you prevent any errors because of writing the R code in .NET (in rpy there where some problems with that, e.g. data.frame was not allowed). Hope this helps!

Resources