0

I have been reading up about the difference between & and && in R.

I understand that, unlike in other languages where & is for bitwise operations and && is used for conditions like height > 150 && height < 180, in R, both are for the latter. For bitwise, there are other functions such as bitwAnd(a, b)

However, what's the difference between & and &&. From what I've read, all I have understood is that "The longer form(&& I guess) is appropriate for programming control-flow and typically preferred in if clauses"

However, I was trying out something where one seems to work and the other doesn't?

> which( (df$Cost > 14789) & (df$Cost < 14791) )
[1]  29989  69576 116578 137242 160072
> which( (df$Cost > 14789) && (df$Cost < 14791) )
integer(0)
tubby
  • 2,074
  • 3
  • 33
  • 55

1 Answers1

0

& performs elementwise comparisons in much the same way as arithmetic operators.

&& evaluates left to right examining only the first element of each vector. Evaluation proceeds only until the result is determined.

So in your code

> which( (df$Cost > 14789) & (df$Cost < 14791) )
[1]  29989  69576 116578 137242 160072
> which( (df$Cost > 14789) && (df$Cost < 14791) )
integer(0)

The first statement evaluates the vector elementwise, hence the results. The second only the first element of the vector.

jeborsel
  • 697
  • 4
  • 13
  • I'm sorry jebsel, I don't think I got you there. We use an AND statement, so that all the sub-conditions are evaluated. How does only processing the first sub-condition help? And even if only the first sub-condition was evaluated, it should still evaluate (df$Cost > 14789) and return some results. I don't think I was able to follow you. Please clarify. – tubby Apr 04 '15 at 02:46
  • && evaluated the first element of the vector df$Cost ... for more info read : http://stackoverflow.com/questions/6558921/r-boolean-operators-and as marked as duplicate question above – jeborsel Apr 04 '15 at 02:52