r-novice-inflammation icon indicating copy to clipboard operation
r-novice-inflammation copied to clipboard

use of && vs & -- instructor training contribution

Open hannesbecher opened this issue 2 years ago • 0 comments

Hi there,

I noticed that in the episode "Making Choices" the operators && and || are used while & and | are not introduced. I think in the examples given, these operators can be used interchangeably. Still, I wonder if it might be better to use the latter two.

The reason is that this lesson stresses vectorisation and the use of && and || can lead to unexpected results when used on vectors.

While & and | return pairwise comparisons for each vector index,

> c(T, F) & c(T, T)
[1]  TRUE FALSE

&& and || compare only the first elements of both vectors. So, the fact that the second elements are not both true is missed here:

> c(T, F) && c(T, T)
[1] TRUE

See also ?base::Logic

Hope this is helpful. Hannes

hannesbecher avatar Apr 01 '22 12:04 hannesbecher