Friday 15 July 2011

r - Assigning values from if-else blocks (how does it work?) -


I think you can assign a value with conditional an if-else block.

  y & lt; - if (condition) 1 else 2  

I realize that the use case for this is limited: If you have vectorised the code, you can ifelse instead Function is an executable gain: if-else in case of scalar on my machine 35x faster than ifelse (although you can call it millions of times to note it Need a difference).

It's annoying to me that I can not do this thing because this code works & mdash; I was surprised that it does not just make an error.

Another example shows if the block behaves like a function & mdash; They automatically return the last value in the block (although you can not use the return statement in them.)

  y  
  if (TRUE) sys.frames () #NULL  

Can anyone tell me what's going on hood, please?

me

Let me note that I Why can not work because this code works - I was surprised that it does not just make an error.

Why do you think so? What happens is that we have

  1. y assigning an expression
  2. if that expression is if () .. .
  3. Enter either TRUE or FALSE in trial
  4. one of the two branches is forwarded
  5. Evaluating the related code
  6. Its final value is known as the value on the right
  7. Assume the value I have been y

I think logical


No comments:

Post a Comment