swcarpentry / r-novice-inflammation

Programming with R
http://swcarpentry.github.io/r-novice-inflammation/
Other
161 stars 394 forks source link

use of && vs & -- instructor training contribution #540

Open hannesbecher opened 2 years ago

hannesbecher commented 2 years ago

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