I recently discovered that you can conditionally assign a value with an if-else block.
y <- if(condition) 1 else 2
I realise that the use case for this is limited: if you have vectorised code, you would use the ifelse function instead. There is a performance benefit: if-else runs about 35x faster than ifelse in the scalar case on my machine (though you need to call it millions of times to notice much of a difference).
What is bugging me is that I can't work out why this code works—I was amazed that it doesn't just throw an error.
Another example suggests that if blocks behave like functions—they automatically return the last value in the block (though you can't use a return statement in them).
y <- if(TRUE)
{
y <- 3
4
} # y is 4
Based on this, I guessed that maybe another environment was created when you entered an if block, but this doesn't seem to be the case.
if(TRUE) sys.frames() # NULL
Can anyone tell me what is happening under the hood, please?