R Programming - if condition execution - r

I am executing following code in R using "IF" and the condition executed (I was expecting, it will give error message),
if("TRUE") print("ok")
can some one help me in understanding the logic behind the code execution?
My understanding is that "if statement" will execute when the conditional expression is true.
In the above code, I have given character as input, but the if condition is executed, which surprise me.

R converts the argument of if statement if it is interpretable as logical. In this case "TRUE" is interpretable as logical. Please see that as.logical("TRUE") returns TRUE. However, if("HELLO") print("ok") would not work and you will get the error:
Error in if ("HELLO") print("ok") :
argument is not interpretable as logical

You just need to fix the error in your syntax. Try this:
if (TRUE){
print("ok")
}

Related

Change "Error" label in stop function on R

Is it possible to change the Error label inside the stop() function?
For example:
stop("This is a error!")
Error: This is a error!
change to:
Incorrect: This is a error!
I need to use stop function, not warning or message functions.
There's a risk that this could be confusing for users seeing something that's an stopping the code without explicitly announcing that it's an error.
If you can guarantee that the user is using English, you can hack it a bit using the backspace character (\b) with:
stop("\b\b\b\b\b\b\bIncorrect: This is a error!")
but this relies on knowing how long the word "Error" is in English, a version that also works in other languages would be trickier.
Edited to add that even in English this doesn't work from inside a function:
throw_an_error <- function()stop("\b\b\b\b\b\b\bIncorrect: This is a error!")
throw_an_error()
# Error in throw_an_errIncorrect: This is a error!

How to target exception-handling to specific exceptions?

Does R provide any support for targetting exception handling to only specific exceptions?
In Python, for example, one can narrow down exception-handling to specific exception types; e.g.:
try:
return frobozz[i]
except IndexError:
return DEFAULT
In this example, the exception handling will kick in only if i is an integer such that i >= len(frobozz) or i < -len(frobozz), but will not catch the exception resulting from, e.g., the case where i is the string "0" (which would be a TypeError, rather than an IndexError).
Wellllll...yes and no, and mostly no.
Every Python exception is wrapped in a particular error class which derives from Error, and Python modules are supposed to raise the "right" kinds of errors. For instance, an index out of range error should throw IndexError. The base language knows about these errors and so you can catch the appropriate error type in your except... clause.
R doesn't do that. Errors are untyped; there's no essential difference between an index out of bounds error and any other error.
That said, you can cheat under certain, very limited, circumstances.
> y <- tryCatch(x[[2]], error = function(e) e)
> y
<simpleError in x[[2]]: subscript out of bounds>
> y$message
[1] "subscript out of bounds"
The key here is the use of the tryCatch function and the error clause. The error clause in a tryCatch is a function of one variable which can perform arbitrary operations on e, which is an object of type 'simpleError' and contains an item named "message". You can parse message and handle interesting cases separately
> y <- tryCatch(x[[2]],
error = function(e) {
if ('subscript out of bounds' == e$message) return(NA) else stop(e))
})
> y
[1] NA
This only works if you can actually detect the error string you want to look for, and that isn't guaranteed. (Then again, it also isn't guaranteed in Python, so things aren't really much different from one another.)
Final question, though: why in Heaven's name are you doing this? What are you really trying to do?

stopifnot() vs. assertError()

I wonder what the differences between stopifnot() and assertError() are:
assertError() is not found by default (You'll have to load the "tools" package first), but stopifnot() is.
More significantly, assertError() always throws an error message, even if I pass arguments like TRUE or FALSE, while stopifnot() does the obvious and expected thing.
Reading the manual page did not help. What is the correct use instead of assertError(length(x) != 7)? If x is undefined, the statement produces no error, but as soon as it is defined, it is producing errors, independent of the length of x (7 or not).
The main difference is where they should be used.
stopIfnot aim at stopping an execution if some conditions are not met during the run where assertError aim at testing your code.
assertError expect it's parameter to raise an error, this is what happens when x is not defined, there's an error
> length(x) != 7
Error: object 'x' not found
When you pass this expression to assertError, it raise an error and assertError return the conditions met (the error in itself). This allow you to test the failure cases of your code.
So assertError is mostly used in tests cases in a Test Driven Development pattern (TDD), when your code/function is supposed to raise an error for some specific parameters and ensure when you update your function later you're not breaking it.
Example usage of stopifnot and assertError:
mydiv <- function(a,b) {
stopifnot(b>0)
a/b
}
And now lets make a test to ensure this will raise an error if we pass "b" as 0:
tryCatch(
assertError(mydiv(3,0)),
error = function(e) { print("Warning, mydiv accept to divide by 0") }
)
Running this code produce no output, desired behavior.
Now if we comment the stopifnot in mydiv like this:
mydiv <- function(a,b) {
#stopifnot(abs(b)>0)
a/b
}
And testing again the tryCatch block, we get this output:
[1] "Warning, mydiv accept to divide by 0"
This is a small example of testing a function really throw an error as expected.
The tryCatch block is just to showcase with a different message, I hope this give more light on the subject.

How to mix flog.fatal and stop

I am starting to use the futile.logger package. There is a nice FATAL error logging that I would like to use in conjuction with stop.
But say I do :
stop(flog.fatal('crash for some reason'))
I get
[FATAL] [2015-07-06 22:46:54] [base.stop] crash for some reason
Error:
[FATAL] [2015-07-06 22:46:54] [base.stop] crash for some reason
How can I just stop (abort the program), after logging what the flog.fatal logged
So [FATAL] [2015-07-06 22:46:54] [base.stop] crash for some reason and that's it
Your question as stated seems trivial? Just do
flog.fatal('crash for some reason'); stop()
?
(I personally find futile.logger more useful for writing text messages to a file, not to the console, but also print the messages to the console with R's conditions message(), warning(), stop() etc.
The value returned by flog.fatal is a character vector (length 1) which stop prints.
res <- flog.fatal('crash for some reason')
print(res)
As alternative you can use ftry function from the futile.logger package.
> futile.logger::ftry(log("a"))
ERROR [2017-08-22 10:50:51] non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function

Debugging unexpected errors in R -- how can I find where the error occurred?

Sometimes R throws me errors such as
Error in if (ncol(x) != 2) { : argument is of length zero
with no additional information, when I've written no such code. Is there a general way for finding which function in which package causes an error?
Since most packages come compressed, it isn't trivial to grep /usr/lib/R/library.
You can use traceback() to locate where the last error occurred. Usually it will point you to a call you make in your function. Then I typically put browser() at that point, run the function again and see what is going wrong.
For example, here are two functions:
f2 <- function(x)
{
if (x==1) "foo"
}
f <- function(x)
{
f2(x)
}
Note that f2() assumes an argument of length 1. We can misuse f:
> f(NULL)
Error in if (x == 1) "foo" : argument is of length zero
Now we can use traceback() to locate what went wrong:
> traceback()
2: f2(x) at #3
1: f(NULL)
The number means how deep we are in the nested functions. So we see that f calls f2 and that gives an error at line 3. Pretty clear. We could reassign f with browser placed just before the f2 call now to check it's input. browser() simply allows you to stop executing a function and look around in its environment. Similar to debug and debugonce except that you don't have to execute every line up until the point you know something goes wrong.
Just to add to what #SachaEpskamp has already suggested, setting options(error=recover) and options(show.error.locations=TRUE) can be extremely helpful when debugging unfamiliar code. The first causes R to launch a debugging session on error, giving you the option to invoke the browser at any point in the call stack up to that error. The second option will tell R to include the source line number in the error.

Resources