Daniel V
Daniel V

Reputation: 1386

is.null on lists vs. other objects

Consider the following scenario:

demo <- list()
is.null(demo$first)
is.null(undefined_object)

The first scenario returns TRUE as it's a NULL element of the list. Why doesn't undefined_object return NULL as it's not an object in the global environment?

Upvotes: 1

Views: 32

Answers (2)

user2554330
user2554330

Reputation: 44877

demo$first calls the function $, and that function returns NULL if the right hand argument is not found.

undefined_object is not a function call, it's just the name of an object, but that object doesn't exist.

If you just print the two expressions, you'll see that they are different:

> demo$first
NULL
> undefined_object
Error: object 'undefined_object' not found

So when you put them in the is.null() call, you get different results, as you saw.

Upvotes: 1

akrun
akrun

Reputation: 887138

If we need a similar TRUE option, one option is to reference that object with .GlobalEnv and check if it is NULL

is.null(.GlobalEnv$undefined_object)
#[1] TRUE

with OP's example, we are checking whether the 'first' is NULL in the environment of 'demo' object which is already created, but the undefined_object is not created and thus we can check it in context with the global environment

is.null(demo$first)
#[1] TRUE
is.null(.GlobalEnv$demo$first)
#[1] TRUE

Upvotes: 1

Related Questions