Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R gotcha: logical-and operator for combining conditions is & not &&

Tags:

Why doesn't subset() work with a logical and && operator combining two conditions?

> subset(tt, (customer_id==177 && visit_date=="2010-08-26")) <0 rows> (or 0-length row.names) 

but they each work individually:

> subset(tt, customer_id==177)  > subset(tt, visit_date=="2010-08-26") 

(Want to avoid using large temporary variables - my dataset is huge)

like image 243
smci Avatar asked Aug 03 '11 21:08

smci


People also ask

When combining the logical operators and and or?

Two or more relations can be logically joined using the logical operators AND and OR . Logical operators combine relations according to the following rules: The ampersand (&) symbol is a valid substitute for the logical operator AND . The vertical bar ( | ) is a valid substitute for the logical operator OR .

Can logical AND relational operators be combined?

Relational operators and logical operators are often used together in logic expressions. Logical operators often combine logical expressions formed from relational operators.

What is the operator for a logical AND condition?

The logical AND ( && ) operator (logical conjunction) for a set of boolean operands will be true if and only if all the operands are true . Otherwise it will be false .

Which operators can be used to combine conditions?

You can use the AND and OR operators to combine two or more conditions into a compound condition. AND, OR, and a third operator, NOT, are logical operators. Logical operators, or Boolean operators, are operators designed to work with truth values: true, false, and unknown.


2 Answers

From the help page for Logical Operators, accessible by ?"&&":

& and && indicate logical AND and | and || indicate logical OR. 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. Evaluation proceeds only until the result is determined. The longer form is appropriate for programming control-flow and typically preferred in if clauses.

(R version 2.13-0)

In other words, when using subset, use the single &.


Here is an illustration of the difference:

c(1,1,0,0) & c(1,0,1,0) [1]  TRUE FALSE FALSE FALSE  c(1,1,0,0) && c(1,0,1,0) [1] TRUE 

If this looks quirky compared to other programming paradigms, remember that R needs to provide a vectorised form of the operator.

like image 189
Andrie Avatar answered Sep 18 '22 06:09

Andrie


In R, you actually want the & operator rather than && to do a pairwise AND operation, the && does a bitwise AND. The same rule applies for OR: if you want to do a logical OR rather than a bitwise OR, you want the | operator.

like image 40
James Thompson Avatar answered Sep 19 '22 06:09

James Thompson