How to find out if a variable is an even number, but not zero?

56 Views Asked by At

I am not sure how to check if a variable is an even number, but more than zero. Is it possible to put 2 conditions for one statement? Is the following wrong?

> if (i %% 2 == 0 & i > 0){
  P_lastround = f-(i/2*P_even + ceiling((i-1)/2)*P_odd)
  Fraction = P_lastround/P_even
} else if (i %% 2 != 0 & i > 0){ 
  P_lastround = f-(P_even*((i-1)/2) + P_even + floor(i/2)*P_odd)
  Fraction = P_lastround/P_odd
} else (i==0) 
{
  P_lastround = f
  Fraction = P_lastround/P_even
}    

I have tried a lot of different values for i and I always get the same answer.

R only reads my else (statement 3), even if it doesn't apply.

2

There are 2 best solutions below

1
Phil On

The following works fine:

test <- function(i) {
  if (i %% 2 == 0 & i > 0) {
    "even"
  } else if (i %% 2 != 0 & i > 0) { 
    "odd"
  } else {
    "zero"
  } 
}

test(0)
[1] "zero"
test(1)
[1] "odd"
test(2)
[1] "even"
1
BoxingIvy On

Thanks everyone! It worked when I removed "(i==0)" in "else (i==0)".