Reputation: 31741
I am trying to test if a list contains an object (github source). This is.null
function has worked so far except in the case where I am testing an item with a name that is a partial match to a non-nul item.
x <- list(ab = 1)
is.null(x$ab)
[1] FALSE ## expected
is.null(x$b)
[1] TRUE ## expected
is.null(x$c)
[1] TRUE ## expected
is.null(x$a)
[1] FALSE ## unexpected
Is this expected behavior for the is.null
function? I don't see any indication in the documentation.
Would it be better to use the exists
function, or some other approach? (I haven't used exists
because it won't work in a loop like for(i in 'a') is.null(x[[i]])
.
Upvotes: 2
Views: 261
Reputation: 43255
look at x$a
. This returns 1
due to partial name matching. So is.null(x$a)
is FALSE
since R matches a
with ab
. If you use [[
notation, you'll get the expected result: is.null(x[['a']])
.
Upvotes: 8