R字符值为null,但未通过is.null()测试

R字符值为null,但未通过is.null()测试,r,R,值不为null,但声明为null时出现非常奇怪的错误,即使在is.null()测试中它的计算结果为FALSE。见下文。在本例中,pid似乎为null,但测试失败,导致代码中出现各种“下一步”问题 > pid <- system2('ps', args = "-ef | grep 'ssh -f' | grep -v grep | tr -s ' ' | \ cut -d ' ' -f 3", stdout = TRUE) > pid character(0) > is.n

值不为null,但声明为null时出现非常奇怪的错误,即使在is.null()测试中它的计算结果为FALSE。见下文。在本例中,pid似乎为null,但测试失败,导致代码中出现各种“下一步”问题

> pid <- system2('ps', args = "-ef | grep 'ssh -f' | grep -v grep | tr -s ' ' | \ cut -d ' ' -f 3", stdout = TRUE)
> pid
character(0)
> is.null(pid)
[1] FALSE
> if(!is.null(pid) && nchar(pid)) {cat('got some pid')}
Error in if (!is.null(pid) && nchar(pid)) { : 
  missing value where TRUE/FALSE needed
> if(!is.null(pid)) {cat('got some pid? Really?')}
got some pid? Really?
操作系统的完整版本:

Linux rserver 3.16.0-44-generic #59~14.04.1-Ubuntu SMP Tue Jul 7 15:07:27 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
最后,我只想运行以下代码:

> if (nchar(pid) > 0) {
+     cat('do something\n')
+ }
Error in if (nchar(pid) > 0) { : argument is of length zero

事实上,您有一个空字符变量并不意味着它是空的。下面是一个例子:

pid <- character()
> pid
character(0)
> is.null(pid)
[1] FALSE
> pid <- NULL
> pid
NULL
> is.null(pid)
[1] TRUE
pid
字符(0)
>is.null(pid)
[1] 假的
>pid
无效的
>is.null(pid)
[1] 真的

nchar()
不返回逻辑值,它返回一个整数值,在本例中它是
整数(0)
。例如,使用
if(TRUE&&nchar(character(0)))“a”
时,您会在if(TRUE&&nchar(character(0))“a”中得到相同的错误
错误:缺少需要TRUE/FALSE的值
,根据nchar(pid)是否为零或更大,该值仍应计算为TRUE或FALSE。在我的例子中,is.null(nchar(pid))也表示FALSE。换句话说,nchar(pid)的输出不是空值。更改为if(nchar(pid)>0{}不会更改错误。为
NULL
和长度为0是完全不同的。您可能希望更改
is.NULL(pid)
条件,使
length(pid)==0
(如上面的注释所示)。那么,正确的检查[如果条件]让我的代码在这种情况下正常运行?我的if(nchar(pid)>0{}仍然抱怨说“if(nchar(pid)>0中的错误:{:参数的长度为零”。也许你可以尝试
length(pid)==0
。这不应该抛出错误,但对于空向量返回
TRUE
。@user3949008-我想你可能想在
if()中使用
length(x)
语句。如果它的计算结果为零,则为false,否则为true。因此您可以安全地执行
!length(x)
pid <- character()
> pid
character(0)
> is.null(pid)
[1] FALSE
> pid <- NULL
> pid
NULL
> is.null(pid)
[1] TRUE