Using F for FALSE sometimes fails [duplicate] - r

This question already has an answer here:
Error in read.table: !header: invalid argument type
(1 answer)
Closed 3 years ago.
I just noticed that I now have to explicitly state FALSE when using such functions as read.csv or setting printFlag to FALSE in mice. Is this an update to RStudio or just a bug?
Sample:
read.csv(text="1,S0006,C000124,12Jan2017,179,7296
2,S0002,C000124,26Feb2017,109,7941
3,S0008,C000124,22Feb2017,190,4511
4,S0006,C000124,03Jan2017,150,7296
5,S0005,C000124,08Feb2017,120,5812
6,S0003,C000124,26Apr2017,46,7512",header=F)
fails with:
Error in !header : invalid argument type
which can then be fixed by setting header=FALSE
RStudio: $version
[1] ‘1.1.463’
R: 3.5.3RC

I can almost replicate this (not quite the same error message) by assigning a character value to F:
F <- "abc"
read.csv(text="1,S0006,C000124,12Jan2017,179,7296
2,S0002,C000124,26Feb2017,109,7941
3,S0008,C000124,22Feb2017,190,4511
4,S0006,C000124,03Jan2017,150,7296
5,S0005,C000124,08Feb2017,120,5812
6,S0003,C000124,26Apr2017,46,7512",header=F)
Error in !header : invalid argument type
using FALSE instead of F is a good idea (for precisely this reason); you could also try rm(F) and see if that allows your original code to work.

Related

Recursive default argument reference [duplicate]

This question already has an answer here:
Unexpected behaviour with argument defaults
(1 answer)
Closed 5 years ago.
Can anyone explain me what is wrong in this code below. What I thought I am doing here is
a declaration of a global variable a=5
a definition of a function fun which takes one argument which defaults to the aforementioned global variable a
And when I call fun() without any parameters the local variable a becomes a copy of the global variable a and at any point in the function code it takes precedence over the global a (unless I specifically use get("a", envir=parent.frame))
But I must be wrong. Why isn't it allowed?
> a = 5
> fun = function(a=a) { a + 1 }
> fun(4)
[1] 5
> fun()
Error in fun() :
promise already under evaluation: recursive default argument reference or earlier problems?
And when I call fun() without any parameters the local variable a becomes a copy of the global variable a
No: default arguments are evaluated inside the scope of the function. Your code is similar to the following code:
fun = function(a) {
if (missing(a)) a = a
a + 1
}
This makes the scoping clearer and explains why your code doesn’t work.
Note that this is only true for default arguments; arguments that are explicitly passed are (of course) evaluated in the scope of the caller.

R package 'checkmate': testString is successful for vector but not assertString, why?

I am currently reading the documentation for checkmate package and I find an issue when dealing with a vector of strings.
testString(letters)
#FALSE
assertString(letters)
#Error in assertString(letters) :
#Assertion on 'letters' failed: Must have length 1.
It seems that assertString does not support test on vectors. Why is that? Any idea is welcome.
The documentation in assertString states that "a string is defined as a character scalar." The function you are seeking is assertCharacter.
assertString is just a shortcut for assettCharacter (x, len =1)

R - Assigning "NA" to objects 'not found' inside a function; is it possible?

I am running a data set (in the example, "data object ") through several different functions in R and concatenating the numeric results at the end. See:
a<-median((function1(x=1,dataobject,reps=500)),na.rm=TRUE)
b<-median((function2(x=1,dataobject,reps=500)),na.rm=TRUE)
c<-median((function3(x=1,dataobject,reps=500)),na.rm=TRUE)
d<-median((function4(x=1,dataobject,reps=500)),na.rm=TRUE)
e<-median((function5(x=1,dataobject,reps=500)),na.rm=TRUE)
f<-median((function6(x=1,dataobject,reps=500)),na.rm=TRUE)
c(a,b,c,d,e,f)
However, some of the functions cannot be run with the data set I am using, and so they return an error; e.g. "function3" can't be run so when it gets to the concatenation step it gives "Error: object 'e' not found" and does not return anything. Is there any way to tell R at the concatenation step to assign a value of "NA" to an object that is not found and continue to run the rest of the code instead of stopping? So that the return would be
[1] 99.233 75.435 77.782 92.013 NA 97.558
A simple question, but I could not find any other instances of it being asked. I originally tried to set up a function to run everything and output the concatenated results, but ran into the same problem (when a function can't be run, the entire wrapper function stops as well and I don't know how to tell R to skip something it can't compute).
Any thoughts are greatly appreciated! Thanks!
A couple of solutions I can think of,
Initialize all the variables you plan to use, so they have a default value that you want.
a = b = c = d = e = NA
then run your code. If an error pops up, you will have NA in the variable.
Use "tryCatch". If you are unaware what this is, I recommend reading on it. It lets you handle errors.
Here is an example from your code,
tryCatch({
a<-median((function1(x=1,dataobject,reps=500)),na.rm=TRUE)
},
error = function(err){
print("Error in evaluating a. Initializing it to NA")
a <<- NA
})

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.

How can I determine if try returned an error or not?

I am trying to do the following:
try(htmlParse(ip[1], T),
where I define a as:
ip[1] = paste('http://en.wikipedia.org/wiki/George_Clooney')
I want to check if the htmlParse worked or not. For many names in my list, there will be no wikipedia sites and thus I need to be able to check and replace ip[1] with NA if the wiki pages does not exist.
Can someone please advise how I can do that. I tried using the command geterrmessage(), however I am not sure how to flush that everytime I change the name of the celebrity.
Currently I have the following:
if(!isTRUE(as.logical(grep(ip[1],err)))) {
ip[1] = NA
}
else {
This is definately incorrect as it is not running the logical statement I want.
Thanks
Amar
This simple example should help you out, I think:
res <- try(log("a"),silent = TRUE)
class(res) == "try-error"
[1] TRUE
The basic idea is the try returns (invisibly) an object of class "try-error" when there's an error. Otherwise, res will contain the result of the expression you pass to try. i.e.
res <- try(log(2),silent = TRUE)
res
[1] 0.6931472
Spend some time reading ?try carefully, including the examples (which aren't as simple as they could be, I guess). As GSee notes below, a more idiomatic way to check if an error is thrown is to use inherits(res,'try-error').
I would try to download all the names (existing or not) from wiki and save it in separate files.I would then grep the following string Wikipedia does not have an article with this exact name and for the non-existing ones I would get a TRUE value. In this way I believe you'll make sure whether the parser worked or the name didn't exist. Additionally you can sort the downloaded files based on their size in case you are suspecting that something went wrong. Corrupted ones have smaller size.
Additionally I would use tryCatch function in order to treat the logical status:
x<-3
tryCatch(x>5,error=print("this is an error"))
Here's a function that evaluates an expression and returns TRUE if it works and FALSE if it doesn't. You can also assign variables inside the expression.
try_catch <- function(exprs) {!inherits(try(eval(exprs)), "try-error")}
try_catch(out <- log("a")) # returns FALSE
out # Error: object 'out' not found
try_catch(out <- log(1)) # returns TRUE
out # out = 0

Resources