[R] Testing for whole numbers

Martin Maechler maechler at stat.math.ethz.ch
Thu Apr 17 18:05:55 CEST 2003


>>>>> "Tamas" == Tamas Papp <tpapp at axelero.hu>
>>>>>     on Thu, 17 Apr 2003 16:47:30 +0200 writes:

    Tamas> Is there a way in R to test if a given number is an integer, ie a
    Tamas> whole number? I am not referring to the data type of a number, but to
    Tamas> its value.

    Tamas> That is to say, is.whole(pi-pi+2) would be TRUE, whereas is.whole(4/3)
    Tamas> would be false. At the moment I am using

    Tamas> is.whole <- function(a) { floor(a)==a }

    Tamas> which is OK for real numbers, but not for complex ones (a+bi would be
    Tamas> a whole number if both a and b are whole). Although it's obvious to
    Tamas> test for the type of the argument and treat it accordingly, I am sure
    Tamas> that there is a function for that in R.

    Tamas> My questions are:

    Tamas> 1. Is there a predefined function for this? I am not trying to
    Tamas> reinvent the wheel, but I have searched help and found nothing
    Tamas> relevant.

No, not in the standard packages at least.
Following your original, I'd recommend to use

is.whole <- function(a) { 
   (is.numeric(a) && floor(a)==a) ||
   (is.complex(a) && floor(Re(a)) == Re(a) && floor(Im(a)) == Im(a))
}

or rather something like

is.whole <- function(a, tol = 1e-7) { 
   is.eq <- function(x,y) { 
	 r <- all.equal(x,y, tol=tol)
	 is.logical(r) && r 
   }
   (is.numeric(a) && is.eq(a, floor(a))) ||
   (is.complex(a) && {ri <- c(Re(a),Im(a)); is.eq(ri, floor(ri))})
}


    Tamas> 2. Would it make sense to propose the extension of
    Tamas> floor, trunc etc to complex numbers? It would
    Tamas> certainly make my life easier in many situations.

It would make sense to propose, yes.
[ Actually maybe another nice test bed for using S4 methods? ]
Even better, if you'd provide the necessary code patches.

But, then, you'd find that R (as well as the other S
implementations) are lacking much of complex number computing
facilities you might want to dream of.
To provide some of these would require a *lot* of more source
code, though that's not true for floor.
One reason for the lack of extensive complex support has been
the rare use of it in (main stream) statistics.
But, as said above:  Improvements are welcome!

Martin Maechler <maechler at stat.math.ethz.ch>	http://stat.ethz.ch/~maechler/
Seminar fuer Statistik, ETH-Zentrum  LEO C16	Leonhardstr. 27
ETH (Federal Inst. Technology)	8092 Zurich	SWITZERLAND
phone: x-41-1-632-3408		fax: ...-1228			<><



More information about the R-help mailing list