Logical operators in R

December 14, 2010

(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)
> z[(z>2) & (z<5)]
[1] 3 4

but the double “&&” gives

> (z > 2) && (z < 5)
> 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)

is equivalent to:

> (z[1] > 2) & (z[1] < 5)

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 .

To leave a comment for the author, please follow the link and comment on their blog: Why? » R.

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

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , , ,

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)