How to test if list element exists?

前端 未结 7 2017
臣服心动
臣服心动 2020-11-30 21:54

Problem

I would like to test if an element of a list exists, here is an example

foo <- list(a=1)
exists(\'foo\') 
TRUE   #foo does exist
exists(\'         


        
相关标签:
7条回答
  • 2020-11-30 22:48

    This is actually a bit trickier than you'd think. Since a list can actually (with some effort) contain NULL elements, it might not be enough to check is.null(foo$a). A more stringent test might be to check that the name is actually defined in the list:

    foo <- list(a=42, b=NULL)
    foo
    
    is.null(foo[["a"]]) # FALSE
    is.null(foo[["b"]]) # TRUE, but the element "exists"...
    is.null(foo[["c"]]) # TRUE
    
    "a" %in% names(foo) # TRUE
    "b" %in% names(foo) # TRUE
    "c" %in% names(foo) # FALSE
    

    ...and foo[["a"]] is safer than foo$a, since the latter uses partial matching and thus might also match a longer name:

    x <- list(abc=4)
    x$a  # 4, since it partially matches abc
    x[["a"]] # NULL, no match
    

    [UPDATE] So, back to the question why exists('foo$a') doesn't work. The exists function only checks if a variable exists in an environment, not if parts of a object exist. The string "foo$a" is interpreted literary: Is there a variable called "foo$a"? ...and the answer is FALSE...

    foo <- list(a=42, b=NULL) # variable "foo" with element "a"
    "bar$a" <- 42   # A variable actually called "bar$a"...
    ls() # will include "foo" and "bar$a" 
    exists("foo$a") # FALSE 
    exists("bar$a") # TRUE
    
    0 讨论(0)
提交回复
热议问题