How to test if list element exists?

前端 未结 7 2075
臣服心动
臣服心动 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:45

    One solution that hasn't come up yet is using length, which successfully handles NULL. As far as I can tell, all values except NULL have a length greater than 0.

    x <- list(4, -1, NULL, NA, Inf, -Inf, NaN, T, x = 0, y = "", z = c(1,2,3))
    lapply(x, function(el) print(length(el)))
    [1] 1
    [1] 1
    [1] 0
    [1] 1
    [1] 1
    [1] 1
    [1] 1
    [1] 1
    [1] 1
    [1] 1
    [1] 3
    

    Thus we could make a simple function that works with both named and numbered indices:

    element.exists <- function(var, element)
    {
      tryCatch({
        if(length(var[[element]]) > -1)
          return(T)
      }, error = function(e) {
        return(F)
      })
    }
    

    If the element doesn't exist, it causes an out-of-bounds condition caught by the tryCatch block.

提交回复
热议问题