# Logical operators in R

December 14, 2010
By

(This article was first published on Why? » R, and kindly contributed to R-bloggers)

A logical operator

In R, the operators “|” and “&” indicate the logical operations OR and AND. For example, to test if x equals 1 and y equals 2 we do the following:

 > x = 1; y = 2 > (x == 1) & (y == 2) [1] TRUE

However, if you are used to programming in C you may be tempted to write
 #Gives the same answer as above (in this example...) > (x == 1) && (y == 2) [1] TRUE 
At this point you could be lulled into a false sense of security and believe that they could be used interchangeably. Big mistake.

Let’s consider another example, this time a vector comparison:
 > z = 1:6 > (z > 2) & (z < 5) [1] FALSE FALSE TRUE TRUE FALSE FALSE > z[(z>2) & (z<5)] [1] 3 4 
but the double “&&” gives
 > (z > 2) && (z < 5) [1] FALSE > z[(z > 2) && (z < 5)] integer(0)#Probably not what you want 
It’s all gone a bit pear shaped! In fact it could have been worse:
 > (z > 2) && (z < 5) [1] TRUE > z[(z > 0) && (z < 5)] [1] 1 2 3 4 5 6 
Now you’ve the wrong answer and something that would be very tricky to spot. This is because R recylces the TRUE variable.

## What’s the difference?

Well from the R help page:

“The longer form evaluates left to right examining only the first element of each vector”

where the longer form refers to “&&”.  So
 > (z > 2) && (z < 5) [1] FALSE 
is equivalent to:
 > (z[1] > 2) & (z[1] < 5) [1] FALSE 
The same concept applies to the OR operator, “|”.

## What do you use the double operator for?

To be honest, I’m not sure. I can think of a few contrived situations, but nothing really useful. The R help page isn’t that enlightening either. If anyone has suggestions please feel free to leave a comment and I’ll update this section.

Note: if you read this post through R-bloggers, then you won’t get any of the updates/comments. You can either subscribe directly to the RSS feed for this blog, or occasionally check the web page .

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...