我的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)
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)
伊恩把这个放在评论中,但我认为这是一个很好的答案:
if (exists("aVariable"))
{
do whatever
}
Run Code Online (Sandbox Code Playgroud)
请注意引用变量名称.
我也看过:
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 而不是错误。