Hi "Deirdh",

You may use ?split() to return a list:

x <- 51:80
lst1 <- lapply(split(seq_along(x), x%%2),function(x1) x[x1]) 
lst1
#$`0`
# [1] 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80

#$`1`
# [1] 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79
sapply(lst1,mean,na.rm=TRUE)
# 0  1 
#66 65 


#odd
mean(x[!!x%%2],na.rm=TRUE)
#[1] 65
#even 
mean(x[!x%%2],na.rm=TRUE)
#[1] 66

A.K.


Thank, this is some of the clearest instruction I see (as a newcomer to R).
Can you also tell me how to return a list, detailing the value of the Odd or 
Even number?

(my task is to read data from a file, take the odd numbers only,  return the 
average value of the odd numbers and I'm struggling)
D 
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

______________________________________________
R-help@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.

Reply via email to