3

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 ?

Julian Wittische
  • 1,219
  • 14
  • 22
  • 5
    The best thing you can do is experiment on your own to see how each of these operators acts on a scalar as well as a vector. – Carl Witthoft Nov 21 '13 at 13:24

3 Answers3

4

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 
James
  • 65,548
  • 14
  • 155
  • 193
4

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.

shadow
  • 21,823
  • 4
  • 63
  • 77
-2

Control flow statement expect condition to be a Boolean (or something which can be converted to it). The first operator | doesn't return a Boolean but a Vector of Boolean, so as such is not meant to be used in condition. The || operator returns a Boolean making it suitable for control flow.

mb14
  • 22,276
  • 7
  • 60
  • 102
  • In R (almost) everything is a vector. And the return value of `||` is a logical (atomic) vector of length 1. – Roland Nov 21 '13 at 14:11