I am trying to divide a number by the sum of the result of two if statements. For some reason, R ignores the parentheses around both the if statements after completing the first if statement and does the division on just the first if statement. When adding parentheses around the first if statement, the formula works as expected. Question is: why is that?
Replacing the if statements with ifelse(y==2,4,1) solves it, as well as the extra parentheses. I am curious why the first test gives me the unexpected result.
x <- 1
y <- 2
z <- 4
test1 <- z/(if(y==2){4}else{1}+if(x==1){4}else{1})
> print(test1)
[1] 1
test2 <- z/((if(y==2){4}else{1})+if(x==1){4}else{1})
> print(test2)
[1] 0.5
I would expect the outcome of test1 and test2 both to be 0.5
Aucun commentaire:
Enregistrer un commentaire