Reputation: 547
I have the following if-else block and want to store its result in a variable.
x <- round(runif(100, -50, 50))
maxD <- 30
check1 <- T
y <- {
if(x > 0 && !check1) pmax(pmin(x, maxD), 0) else if(x < 0 && check1) x else 0
}
Given that check1 == T
, I'd expect y
to be between -50
and 0
, but the code doesn't seem to cut the values > 0. Why?
Also if I change check1 = F
, then the output is a single value. But when I restart R and rerun the code (with check1 = F
) I get a vector. When I change the value of check1
again and then again, I suddenly get a single value. It is also often different after I restart R. This seems kinda arbitrary. What's happening here?
Upvotes: 0
Views: 60
Reputation: 18541
The problem is that x
is a vector, but &&
does't work with vectors. It will only evaluate the first element.
c(TRUE, FALSE) && TRUE
[1] TRUE
Given further that you generate x
randomily with runif
you will get a different result every time you run this code.
Upvotes: 3