why does is.null return false for a non-existent list element?

回眸只為那壹抹淺笑 提交于 2019-12-11 00:24:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!