代码之家  ›  专栏  ›  技术社区  ›  Yannick Wurm

替代“!在R中为.null()

r
  •  45
  • Yannick Wurm  · 技术社区  · 16 年前

    我的R代码最终包含过多的以下形式的语句:

    if (!is.null(aVariable)) { 
         do whatever 
    }
    

     if (is.defined(aVariable)) { 
          do whatever 
     }
    

    做一个 is.defined

    干杯

    6 回复  |  直到 16 年前
        1
  •  40
  •   Alex Brown    16 年前

    您最好先确定函数或代码接受的值类型,然后询问:

    if (is.integer(aVariable))
    {
      do whatever
    }
    

    或者,只需制作您想要的功能:

    is.defined = function(x)!is.null(x)
    
        2
  •  21
  •   Etienne Racine    7 年前

    如果只是一个简单易读的问题,您可以随时定义自己的函数:

    is.not.null <- function(x) !is.null(x)
    

    因此,您可以在整个程序中使用它。

    is.not.null(3)
    is.not.null(NULL)
    
        3
  •  10
  •   JD Long    16 年前

    if (exists("aVariable"))
    {
      do whatever
    }
    

        4
  •  7
  •   Brandon Bertelsen    8 年前

    我还看到:

    if(length(obj)) {
      # do this if object has length
      # NULL has no length
    }
    

    character(0) , logical(0) , integer(0)

        5
  •  3
  •   bdetweiler    7 年前

    要处理未定义的变量以及空值,可以使用 substitute deparse :

    nullSafe <- function(x) {
      if (!exists(deparse(substitute(x))) || is.null(x)) {
        return(NA)
      } else {
        return(x)
      }
    }
    
    nullSafe(my.nonexistent.var)
    
        6
  •  2
  •   sgrubsmyon    9 年前

    这个 shiny 软件包提供了方便的功能 validate() need() 用于检查变量是否可用且有效。 需要() 计算表达式的值。如果表达式无效,则返回错误消息。如果表达式有效, NULL 他回来了。可以使用它来检查变量是否有效。看见 ?need

    我建议定义如下函数:

    is.valid <- function(x) {
      require(shiny)
      is.null(need(x, message = FALSE))  
    }
    

    is.valid() 会回来的 FALSE x 错误的 , , NA NaN ,一个空字符串 "" ,空的原子向量,只包含缺失值的向量,只包含 错误的 try-error . 在所有其他情况下,它都会返回 TRUE .

    也就是说, (及 )涵盖了非常广泛的故障案例。而不是写:

    if (!is.null(x) && !is.na(x) && !is.nan(x)) {
      ...
    }
    

    你可以简单地写下:

    if (is.valid(x)) {
      ...
    }
    

    带着上课的支票 试错 ,它甚至可以与 try() 块以静默方式捕获错误:(请参阅 https://csgillespie.github.io/efficientR/programming.html#communicating-with-the-user )

    bad = try(1 + "1", silent = TRUE)
    if (is.valid(bad)) {
      ...
    }