[R] how to test for the empty set

Steven McKinney smckinney at bccrc.ca
Tue Nov 25 03:46:32 CET 2008


Dear Jay,

length(x) will return zero
for all these (vector) examples,
and is quite readable in code.
(You might have seen code such as
if(length(x)) { blah }
which uses this idea.) 

Does this cover all your use
cases?


> x <- c()

> class(x)
[1] "NULL"

> length(x)
[1] 0

> y <- letters[1:3]
> z <- letters[4:6]
> x <- intersect(y,z)

> class(x)
[1] "character"

> length(x)
[1] 0

> y <- 1:3
> z <- 4:6
> x <- intersect(y,z)

> class(x)
[1] "integer"

> length(x)
[1] 0
> 


HTH

Steven McKinney

Statistician
Molecular Oncology and Breast Cancer Program
British Columbia Cancer Research Centre

email: smckinney +at+ bccrc +dot+ ca

tel: 604-675-8000 x7561

BCCRC
Molecular Oncology
675 West 10th Ave, Floor 4
Vancouver B.C. 
V5Z 1L3
Canada




-----Original Message-----
From: r-help-bounces at r-project.org on behalf of G. Jay Kerns
Sent: Mon 11/24/2008 9:41 AM
To: r-help at r-project.org
Subject: [R] how to test for the empty set
 
Dear R-help,

I first thought that the empty set (for a vector) would be NULL.

x <- c()
x

However, the documentation seems to make clear that there _many_ empty
sets depending on the vector's mode, namely, numeric(0), character(0),
logical(0), etc.  This is borne out by

y <- letters[1:3]
z <- letters[4:6]
intersect(y,z)

which, of course, is non-NULL:

is.null(character(0))   # FALSE

So, how can we test if a vector is, say, character(0)?  The following
doesn't (seem to) work:

x <- character(0)
x == character(0)  # logical(0)

More snooping led to the following:

wiki.r-project.org/rwiki/doku.php?id=tips:surprises:emptysetfuncs

and at the bottom of the page it says "logical(0) is an empty set,
thus is TRUE".  However, I get

isTRUE(logical(0))   # FALSE

but, on the other hand,

all.equal(x, character(0))  # TRUE

This would seem to be the solution, but am I missing something? and in
particular, is there an elegant way to check in the case that the mode
of the vector is not already known?

Thanks in advance for any insight you may have.

Best,
Jay




***************************************************
G. Jay Kerns, Ph.D.
Associate Professor
Department of Mathematics & Statistics
Youngstown State University
Youngstown, OH 44555-0002 USA
Office: 1035 Cushwa Hall
Phone: (330) 941-3310 Office (voice mail)
-3302 Department
-3170 FAX
E-mail: gkerns at ysu.edu
http://www.cc.ysu.edu/~gjkerns/

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list