r_notes
r_notes copied to clipboard
Point out short circuiting behaviour of double boolean operators
The tutorial points out that &&
and ||
are the scalar variants of &
and |
but doesn't explain why it's useful to have to operators and the more subtle differences. I think it would be worthwhile to point out that
-
&&
and||
don't evaluate the right hand side when not necessary:
> x <- TRUE || stop('Oops')
> x
TRUE
- Using them where you need the vectorized version is dangerous:
> (1:2) && (3:4)
[1] TRUE
> if (all((1:2) && (3:4))) message('Oops')
Oops
Yup, good observations. There are a couple things like that, the other example being assignment to the parent environment with <<-
. However the problem with explaining those is that they are introduced early before function calls or vectorisation. So I cannot just drop stop()
or 1:2
there. And returning to the same operators later doesn't flow well.
For now I just left them there and curious readers will find out with help()
. But will leave this issue hanging, maybe some way of explaining them will come to mind. Or maybe someone will have good suggestions.