问题
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]]).
回答1:
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']]).
来源:https://stackoverflow.com/questions/17349485/why-does-is-null-return-false-for-a-non-existent-list-element