Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between | and || in R [duplicate]

Tags:

operators

r

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 ?

like image 602
Julian Wittische Avatar asked May 12 '26 00:05

Julian Wittische


2 Answers

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 
like image 116
James Avatar answered May 14 '26 13:05

James


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.

like image 41
shadow Avatar answered May 14 '26 15:05

shadow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!