R中"!is.null()"的替代

Yan*_*urm 53 r

我的R代码最终包含多种形式的语句:

if (!is.null(aVariable)) { 
     do whatever 
}
Run Code Online (Sandbox Code Playgroud)

但这种说法很难阅读,因为它包含两个否定.我更喜欢这样的东西:

 if (is.defined(aVariable)) { 
      do whatever 
 }
Run Code Online (Sandbox Code Playgroud)

is.defined与!is.null相反的类型函数是否在R中存在标准?

欢呼,yannick

Ale*_*own 34

您最好不要计算出您的函数或代码接受的值类型,并要求:

if (is.integer(aVariable))
{
  do whatever
}
Run Code Online (Sandbox Code Playgroud)

这可能是对isnull的改进,因为它提供了类型检查.另一方面,它可能会降低代码的通用性.

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

is.defined = function(x)!is.null(x)
Run Code Online (Sandbox Code Playgroud)

  • 名称`is.defined`不太正确,因为您可以使用值"NULL"声明变量.试试,例如`x < - NULL; x`.`isnt.null`将是该函数的更合适的名称. (3认同)

Eti*_*ine 16

如果只是一个易于阅读的问题,您可以随时定义自己的功能:

is.not.null <- function(x) !is.null(x)
Run Code Online (Sandbox Code Playgroud)

所以你可以在你的程序中使用它.

is.not.null(3)
is.not.null(NULL)
Run Code Online (Sandbox Code Playgroud)


JD *_*ong 9

伊恩把这个放在评论中,但我认为这是一个很好的答案:

if (exists("aVariable"))
{
  do whatever
}
Run Code Online (Sandbox Code Playgroud)

请注意引用变量名称.

  • 我不认为这是一样的.`exists`测试变量是否绑定.`is.null`假定变量已绑定,并测试其内容是否为NULL对象.它们不可互换. (16认同)

Bra*_*sen 7

我也看过:

if(length(obj)) {
  # do this if object has length
  # NULL has no length
}
Run Code Online (Sandbox Code Playgroud)

不过我觉得不是很好。因为某些向量的长度可能为0. character(0), logical(0)integer(0)并且可能会被视为 NULL 而不是错误。