tags:

views:

232

answers:

3

Hello, my R code ends up containing plethora of statements of the form:

if (!is.null(aVariable)) { 
     do whatever 
}

But this kind of statement is hard to read because it contains two negations. I would prefer something like:

 if (is.defined(aVariable)) { 
      do whatever 
 }

Does a is.defined type function that does the opposite of !is.null exist standard in R?

cheers, yannick

+4  A: 

You may be better off working out what value type your function or code accepts, and asking for that:

if (is.integer(aVariable))
{
  do whatever
}

This may be an improvement over isnull, because it provides type checking. On the other hand, it may reduce the genericity of your code.

Alternatively, just make the function you want:

is.defined = function(x)!is.null(x)
Alex Brown
The name `is.defined` isn't quite right since you can declare a variable with the value `NULL`. Try, e.g. `x <- NULL; x`. `isnt.null` would be a more appropriate name for the function.
Richie Cotton
in perl, at least, a variable is considered not defined if it has the value undef, which is like null.
Alex Brown
+1  A: 

Ian put this in the comment, but I think it's a good answer:

if (exists("aVariable"))
{
  do whatever
}

note that the variable name is quoted.

JD Long
I don't think this is the same. `exists` tests whether the variable is bound. `is.null` assumes the variable is bound, and tests whether or not its content is the object NULL. They're not interchangeable.
Harlan
+2  A: 

If it's just a matter of easy reading, you could always define your own function :

is.not.null <- function(x) ! is.null(x)

So you can use it all along your program.

is.not.null(3)
is.not.null(NULL)
Etiennebr