[R] identifying odd or even number
Marc Schwartz
marc_schwartz at me.com
Thu Jul 1 19:10:28 CEST 2010
On Jul 1, 2010, at 10:40 AM, Yemi Oyeyemi wrote:
> Hi, I run into problem when writing a syntax, I don't know syntax that will return true or false if an integer is odd or even.
> Thanks
x <- 1:10
> x
[1] 1 2 3 4 5 6 7 8 9 10
# modulo division
> x %% 2 == 0
[1] FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE
is.even <- function(x) x %% 2 == 0
> is.even(x)
[1] FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE
> is.odd <- function(x) x %% 2 != 0
> is.odd(x)
[1] TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE
Be aware that this will work for integer values. If you have floating point values that are 'close to' integer values, the exact comparison to 0 will be problematic. This may occur as the result of calculations where the result is 'close to' an integer value. In which case, you may want to review:
http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f
HTH,
Marc Schwartz
More information about the R-help
mailing list