This line of code returns TRUE if the file exits or NA if the directory does not exist.
In this case the directory does not exist so this line returns
file.info("M:/T/2014/")[1,"isdir"]
[1] NA
Now I want to catch this case so I do:
if(file.info("M:/T/2014")[1,"isdir"] != TRUE){
print("there is no directory")
}
But I get an error:
Error in if (file.info("M:/T/2014")[1, "isdir"] != TRUE) { :
missing value where TRUE/FALSE needed
I also tried:
if(as.character(file.info("M:/T/2014")[1,"isdir"]) == "NA"){
print("there is no directory")
}
Can you advise what to do to put != TRUE or == "NA" in the if statement?
Thank you.
Try something like this using an is.na statement:
f <- file.info("M:/T/2014/")[1,"isdir"]
if(!is.na(f) && !f) print("there is no directory")
Perhaps, though, you want:
f <- file.info("M:/T/2014/")[1,"isdir"]
if(is.na(f) | !f) print("there is no directory")
Related
In R, I want to create a function that return Flag=0 if it encounters any error:
Error<-function(x){
tryCatch(x,
error=function(e{
Flag=0
}
)
}
When I enter: Error(5+b). It does not reflect Flag=0.
Flag <- 1
tryCatch(
5+b,
error=function(e) { Flag <<- 0}
)
Flag
[1] 0
In your code, the scope of Flag is local to the error handler. Using <<- makes the assignment in the global environment.
You can return a string ('error') here if error occurs and check it's value to return 1/0.
Error<-function(x){
y <- tryCatch(x,error=function(e) return('error'))
as.integer(y != 'error')
}
Error(sqrt('a'))
#[1] 0
Error(sqrt(64))
#[1] 1
Below is the function created to format number.
format_number <- function(num, format_flag = "yes"){
if(format_flag == "yes"){
num <- paste0(num/100,"%")
} else if (format_flag == "no"){
num <- num
}
return(num)
}
However, when I execute format_number(3,2), the answer is 3. Basically it should show an error right? Because 2 is not a valid input. Please advice
2 is valid input. but in your function none of "if" statement will satisfied because 2!='yes' and 2!='no' , then the original value of 'num' will return which is 3.
How would I make this comparison in R?
if (is.null(a)| a == 'LAST') {
# do something
}
If the a is NULL this fails, throwing the error:
Error in if (a == "LAST") { :
argument is of length zero
How could I work around this?
Is it possible in R to do the following:
execute cmd1
if cmd1 generates error, proceed to:
execute cmd2
Thanks
try and/or tryCatch may be of use to you. Consider the super-simple toy example below:
# Our function just returns it's input as long as input is not negative otherwise an error is generated
f <- function(n) {
if( n < 0 )
stop("need positive integer")
return(n)
}
# Our alternative function to run if we get an error from the first function
f2 <- function(n) return( cat( paste( "You have a negative number which is" , n ) ) )
# Now we try to run it with `try`:
if( class( try( f(-1) , silent = TRUE ) ) == "try-error" )
f2(-1)
#You have a negative number which is -1
# And using the sophisticated `tryCatch()`
tryCatch( f(-1) , finally = f2(-1) )
#Error in f(-1) : need positive integer
#You have a negative number which is -1
The return value of try() is the value of the expression if it evaluates without error, otherwise an object of the class "try-error". In the first example we just check to see if an error was generated using comparing the class of the return value of try and execute f2() if an error was generated.
Note there are quite a few ways to handle this and I certainly wouldn't advocate either of these as being the best, but they should be a useful starting point for you to learn more about error handling.
Try this, err is the error message in the try block.
tryCatch(stop(),
error=function(err){
print(1)
print(err)
})
Depending on your use case, even simple short-circuiting of boolean operators might be enough. i.e., if your functions can return TRUE to indicate no-error and FALSE to indicate an error, then you can use the fact that || will only evaluate the RHS operand if the LHS operand evaluates to FALSE.
> doAwesomeStuff <- function() {cat("OMG, I'm awesome! <falls flat on face>\n"); FALSE}
> okDoNormalStuff <- function() {cat("OMG, I'm OK! :-)\n"); TRUE}
> doAwesomeStuff() || okDoNormalStuff()
OMG, I'm awesome! <falls flat on face>
OMG, I'm OK! :-)
[1] TRUE
But if doAwesomeStuff() works,
> doAwesomeStuff <- function() {cat("OMG, I'm awesome!\n"); TRUE}
> doAwesomeStuff() || okDoNormalStuff()
OMG, I'm awesome!
[1] TRUE
A question about this R code:
library(RODBC)
ch <- tryCatch(odbcConnect("RTEST"),
warning=function(w){print("FAIL! (warning)");return(NA)},
error=function(e){print(paste("ERROR:",geterrmessage()));return(NA)})
df <- tryCatch(sqlQuery(ch,"SELECT Test from tblTest"),
warning=function(w){print("FAIL! (warning)");return(NA)},
error=function(e){print(paste("ERROR:",geterrmessage()));return(NA)})
odbcClose(ch)
Code works fine for errors (forced by omitting the required paramaters in the code) in both cases (warning- and error part are almost exactly the same): I get a NA value and an errormessage.
Also for an error with sqlQuery (give an invalid DSN): NA value and an errormessage.
But not for warnings with sqlQuery. No message output, but df contains the message (so no NA). Why?
I checked code for sqlQuery and found this:
stat <- odbcQuery(channel, query, rows_at_time)
if (stat == -1L) {
if (errors)
return(odbcGetErrMsg(channel))
else return(invisible(stat))
}
error is parameter to sqlQuery, on default TRUE, so it gives you character vector without error or warning. If you change it to sqlQuery(ch,"SELECT Test from tblTest",FALSE) then df will contain -1 value. This is error code from C-level, but not error in R meaning so tryCatch could not handle it.
I suppose that you need to check if df==-1 after tryCatch.
I ended up with this code. Now I can handle the specific Mysql error_code:
saveText <- function(query, channel, errors = TRUE) {
stat <- odbcQuery(channel, query)
if (stat == -1L) {
if (errors)
err <- odbcGetErrMsg(channel)
else {
err <- invisible(stat)
}
return(err)
}
}