Member-only story

What You May Take for Granted: The Difference Between & and && in R

Lathan Liou
3 min readSep 8, 2020

--

After reading the article, which one do you think represents a “&” and a “&&”?

If you’ve been using R for a while now, you may have come across the double “&” operator. Most people who’ve coded before, whether in R or some other language, have an intuitive feel for what the “&” represents. It’s a logical AND statement. “The sky is blue AND cows can fly” is a logically false statement because even though the sky is blue, the second part of the statement is false. So what the heck then does a “&&” represent?

If you look up the help page, using?"&&", you will read “& and && indicate logical AND…The shorter form performs elementwise comparisons in much the same way as arithmetic operators. The longer form evaluates left to right examining only the first element of each vector.” What does this mean? Let’s do a quick illustrative example.

x <- 1:3
x > 1 & x < 3
[1] FALSE TRUE FALSE
x > 1 && x < 3
[1] FALSE

This is what you should see in your console. See how the “&&” operator returned a logical vector of length 1; it only looked at the first element, which in this case was “1” and it evaluated to false (it failed the first condition of x>1). We call this behavior in programming lazy evaluation.

So, why is this even useful? Simply put, it’s a matter of efficiency. Let’s use a trivial example where suppose we have a vector of one billion

--

--

Lathan Liou
Lathan Liou

Written by Lathan Liou

Data Scientist at Merck. Tidyverse enthusiast and a neRd.

Responses (1)