I am a big newbie I must confess but I do not understand the difference between those two operators. I read the following, but I have trouble getting it:
"The shorter form performs elementwise comparisons in much the same way as arithmetic operators. The longer form evaluates left to right examining only the first element of each vector. Evaluation proceeds only until the result is determined. The longer form is appropriate for programming control-flow and typically preferred in if clauses."
Why is the second form more appropriate ?
The second form is useful for short-circuiting, possibly avoiding otherwise lengthy computations or errors in the second (or subsequent in lengthier statements) condition.
In particular,
condition || lengthyComputation()
will resolve quickly in the event of condition being TRUE. For example,
system.time(TRUE || {Sys.sleep(1);TRUE})
user system elapsed
0 0 0
system.time(FALSE || {Sys.sleep(1);TRUE})
user system elapsed
0 0 1
The short operates element-wise on vectors and returns a vector of the same size as the input vectors. If necessary it recycles the shorter vector:
> c(FALSE, FALSE) | c(TRUE, FALSE)
[1] TRUE FALSE
The long form only consideres the first element of each vecotr and returns a length-one logical vector.
> c(FALSE, FALSE) || c(FALSE, TRUE, FALSE)
[1] FALSE
Typically whenever you have an if-statement, you need a length-one logical vector as a condition. Since || is faster than |, this version should be prefered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With