Difference between & and && operators in R

r

#1

I was working on a data set while I noticed an issue with the usage of the AND operator in R.

The aim was to determine the indices of the rows which had year=2011, month=1 and day=20.
The following code gave an incorrect output ‘integer(0)’

which((total$year==2011)&&(total$month==1)&&(total$day==20)) integer(0)

However the following code worked quite fine.
which((total$year==2011)&(total$month==1)&(total$day==20)) [1] 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 [15] 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910

Could anyone please elaborate on its reason? Any answers would be highly appreciated.


#2

Below is a snippet from the help page:
http://stat.ethz.ch/R-manual/R-patched/library/base/html/Logic.html

The shorter form performs elementwise comparisons.
The longer form evaluates left to right examining only the first element of each vector.
The longer form is appropriate for programming control-flow and typically preferred in if clauses.


#3

@sonny
Thanks for replying.
I saw the documentation. However, still I am unable to point out why the above mentioned code did not work with ‘&&’ , but it did work with ‘&’.


#4

That is because & works on each element and && doesnt.
Remember && is usually used in control-flow statements like if, while, etc.


#5

Okay. Thanks