[R-sig-teaching] checking even/odd in R

John Fox jfox at mcmaster.ca
Mon Dec 4 03:16:06 CET 2006


Dear Robert and Yeasmin,

You could test that the number mod 2 is 0; e.g.,

> (1:10 %% 2) == 0
 [1] FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE

A potential problem is that testing exact equality is risky, so you're
probably better off checking that abs(x) %% 2 is less than some very small
number such as sqrt(.Machine$double.eps).

I hope this helps,
 John

--------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario
Canada L8S 4M4
905-525-9140x23604
http://socserv.mcmaster.ca/jfox 
-------------------------------- 

> -----Original Message-----
> From: r-sig-teaching-bounces at r-project.org 
> [mailto:r-sig-teaching-bounces at r-project.org] On Behalf Of 
> Robert W. Hayden
> Sent: Sunday, December 03, 2006 8:24 PM
> To: Yeasmin Khandakar
> Cc: R-sig-teaching
> Subject: Re: [R-sig-teaching] checking even/odd in R
> 
> 
> I do not know of anything specific to r but standard 
> programming tricks may do it.  For example, if the number is 
> x, compute y=x/2, let z be y rounded to the nearest whole 
> number, and check if y=z.  If it does, x is even.  There may 
> be rounding issues; I doubt R stores data as integers.  You 
> might have to do this in an environment that sees the numbers 
> as integers -- or text.  AWK comes to mind.
> 
> You may also want code to check for x values like 23.456. 
> 
> > 
> > Dear all,
> > 
> > I'm in search for a function which can be used to check whether a 
> > numeriacl value (say, x) is even/odd.
> > Any help is highly appreciated.
> > 
> > Thanks
> > Yeasmin
> > 
> > --Boundary_(ID_5eoWS9sJoAbqcSKM1OUsmg)
> > Content-Type: text/plain; charset="us-ascii"
> > MIME-Version: 1.0
> > Content-Transfer-Encoding: 7bit
> > Content-Disposition: inline
> > 
> > _______________________________________________
> > R-sig-teaching at r-project.org mailing list 
> > https://stat.ethz.ch/mailman/listinfo/r-sig-teaching
> > 
> > --Boundary_(ID_5eoWS9sJoAbqcSKM1OUsmg)--
> > 
> > 
> 
> 
> 
>  _______
> |   ^  | 		    
> |     /  		    Robert W. Hayden
> |    |   		    in the old library
> |    |   		    212 Main Street
> |   /    	            P. O. Box 450
> |  |     		  ^ North Troy, VT 05859
> L__L			    (802) 988-2587
>                             http://statland.org/      
> Map of VT                   bob at statland.org
> 
> Communications sent to Plymouth State will not reach me.
> 
> _______________________________________________
> R-sig-teaching at r-project.org mailing list 
> https://stat.ethz.ch/mailman/listinfo/r-sig-teaching




More information about the R-sig-teaching mailing list