Gopala
Gopala

Reputation: 10473

R character value is null, but fails is.null() test

Very strange error on a value being not null, but is claimed to be null, even though it evaluates to FALSE on is.null() test. See below. In this case, pid seems to be null, but the test fails, causing me all sorts of 'next step' problems in the code.

> 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?

What does folks think is happening here? Here is my version information of R:

> version
               _                           
platform       x86_64-pc-linux-gnu         
arch           x86_64                      
os             linux-gnu                   
system         x86_64, linux-gnu           
status                                     
major          3                           
minor          2.2                         
year           2015                        
month          08                          
day            14                          
svn rev        69053                       
language       R                           
version.string R version 3.2.2 (2015-08-14)
nickname       Fire Safety         

Full version of the OS:

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

In the end, I simply want this code to run:

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

Upvotes: 3

Views: 1765

Answers (1)

RHertel
RHertel

Reputation: 23788

The fact that you have an empty character variable doesn't mean that it's NULL. Here's an example:

pid <- character()
> pid
character(0)
> is.null(pid)
[1] FALSE
> pid <- NULL
> pid
NULL
> is.null(pid)
[1] TRUE

Upvotes: 4

Related Questions