hadley / strict

Make R a little bit stricter
235 stars 10 forks source link

Don't allow use of && and || on vectors #32

Open mungojam opened 6 years ago

mungojam commented 6 years ago

This one catches me out quite a lot as I've come from another language where && and || are almost exclusively used (since they just mean short-circuit and/or).

x <- c(1,2,3,4,5)
x > 1 && x < 4
#[1] FALSE
x <- c(1,2,3,4,5)
x >= 1 & x < 6
[1] TRUE TRUE TRUE TRUE TRUE

Thanks to @WerthPADOH, I realise now that && and || just check the first item in the same way that if(vector) does. Very dangerous and would be good for it to throw an error

WerthPADOH commented 6 years ago

I realise now that the first one is meant for testing if all elements match

It's actually just returning the first element of a logical vector.

x > 0 && x < 4
[1] TRUE

Still, I agree it makes sense to cover this. Same with if (vector), which is nice enough in base R to warn when a vector's given.

mungojam commented 6 years ago

You're right thanks, convinced myself otherwise with my inconclusive test.

Yeah, covering if(vector) too would be cool, I've hit that too before a few times.

On Mon, 27 Nov 2017, 18:02 Nathan Werth, notifications@github.com wrote:

I realise now that the first one is meant for testing if all elements match

It's actually just returning the first element of a logical vector.

x > 0 && x < 4 [1] TRUE

Still, I agree it makes sense to cover this. Same with if (vector), which is nice enough in base R to warn when a vector's given.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/hadley/strict/issues/32#issuecomment-347269379, or mute the thread https://github.com/notifications/unsubscribe-auth/ADAiy1nZkBy-H_dAQlkmMd8z-n_szNCLks5s6vjGgaJpZM4Qr-lW .