What's the differences between & and &&, | and || in R? [duplicate] - r

This question already has answers here:
Boolean operators && and ||
(4 answers)
Closed 9 years ago.
Why there are four logical operators:
&, &&
|, ||
What's the differences in usage?
Yes, I've checked the docs, yet I'm a little bit confused. The docs says:
‘&’ 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.
I think a piece of example will clearly demonstrate them. Thanks.

Key differences are as below...
Long form(&& or ||) short circuits, which means if it can identify the result by just validating just the first element. While doing &&, if the comparision of first two elements resulted in false, comparing next set of elements will also result in False. So, it returns false. While doing || if comparision resulted in true in first few elements, we can confidently say that any further validations will not change the result so it returns True.
Short forms continues to do for the entire vectors and creates a vector of results and returns it.
Hope this helps.
& 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.
Source: http://stat.ethz.ch/R-manual/R-patched/library/base/html/Logic.html

Related

Apply `&` on a boolean array

I have an array of boolean values and I want to get the logical and of all elements. What is the most efficient way to do that?
I tried
&([true,false,false]...)
but it throws the error:
syntax: malformed expression
Surprisingly (at least to me) the following expression
|([true,false,false]...)
evaluates to true. So how do I do that? Right now I use a bunch of nots to do that, but this is very unsatisfactory.
Also is this actually better than just looping through all the elements?
Most probably this behavior of & is caused by deprecated ccall functionality where & was used in front of a variable. As explained in the comments above:
you can wrap & in parentheses to make it work as expected(&)([true,false,false]...); however, this is not efficient as you have do splat the passed argument;
if your arguments are all Boll then all function is a recommended way to perform logical and;
if you would need bitwise and then reduce(&, [true,false,false]) is a nice solution as phg indicated.

JavaCC - choice based on return type?

I have an ifElse Statement which can be of the following two types
a) ifElse(condition, expression_bool_result, expression_bool_result)
whereas expression_bool_result may either be TRUE/FALSE, the result of and(), or(), ==, !=.... or further ifElse
b) ifElse(condition, expression_arith_result, expression_arith_result)
whereas expression_arith_result may either be any number, the result of calculations of further functions returning a number... (or further ifElse)
Since I am new to javacc, I would like to ask you how a production could look like which allows the parser for a clear decision.
Currently I get the warning
Warning: Choice conflict involving two expansions at
line 824, column 5 and line 825, column 5 respectively.
A common prefix is: "ifElse" "("
Consider using a lookahead of 3 or more for earlier expansion.
which - as far as I can tell - implies that my grammer (regarding ifelse) is ambiguous.
If there is no way to write it unambiguously, how could the suggested lookahead look like?
Thanks for your feedback in advance!
No fixed amount of lookahead could possibly resolve this ambiguity in all cases. You could have an arbitrarily long stream of tokens that form a valid expression_arith_result - but is then followed by a comparison operator and another arithmetic value, thus turning it into an expression_bool_result.
The solution would be to have a single ifElse statement, that takes two arbitrary expressions. The required agreement in type between the two expressions would be a matter of semantics, not grammar.
Jason's answer is correct in that you can't resolve the choice with a fixed length of lookahead. However JavaCC does not limit you to fixed length of lookahead. So you can do the following.
void IfExpression() :
{ }
{ LOOKAHEAD( <IFELSE> "(" Condition() "," BooleanExpression() )
BooleanIfExpression()
|
ArithmeticIfExpression()
}

Why can't I use || and && operators in data.table row selection? [duplicate]

This question already has answers here:
Boolean operators && and ||
(4 answers)
Closed 9 years ago.
Why there are four logical operators:
&, &&
|, ||
What's the differences in usage?
Yes, I've checked the docs, yet I'm a little bit confused. The docs says:
‘&’ 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.
I think a piece of example will clearly demonstrate them. Thanks.
Key differences are as below...
Long form(&& or ||) short circuits, which means if it can identify the result by just validating just the first element. While doing &&, if the comparision of first two elements resulted in false, comparing next set of elements will also result in False. So, it returns false. While doing || if comparision resulted in true in first few elements, we can confidently say that any further validations will not change the result so it returns True.
Short forms continues to do for the entire vectors and creates a vector of results and returns it.
Hope this helps.
& 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.
Source: http://stat.ethz.ch/R-manual/R-patched/library/base/html/Logic.html

General Comparisons vs Value Comparisons

Why does XQuery treat the following expressions differently?
() = 2 returns false (general Comparison)
() eq 2 returns an empty sequence (value Comparison)
This effect is explained in the XQuery specifications. For XQuery 3, it is in chapter 3.7.1, Value Comparisons (highlighting added by me):
Atomization is applied to the operand. The result of this operation is called the atomized operand.
If the atomized operand is an empty sequence, the result of the value comparison is an empty sequence, and the implementation need not evaluate the other operand or apply the operator. However, an implementation may choose to evaluate the other operand in order to determine whether it raises an error.
Thus, if you're comparing two single element sequences (or scalar values, which are equal to those), you will as expected receive a true/false value:
1 eq 2 is false
2 eq 2 is true
(1) eq 2 is false
(2) eq 2 is true
(2) eq (2) is true
and so on
But, if one or both of the operands is the empty list, you will receive the empty list instead:
() eq 2 is ()
2 eq () is ()
() eq () is ()
This behavior allows you to pass-through empty sequences, which could be used as a kind of null value here. As #adamretter added in the comments, the empty sequence () has the effective boolean value of false, so even if you run something like if ( () eq 2) ..., you won't observe anything surprising.
If any of the operands contains a list of more than one element, it is a type error.
General comparison, $sequence1 = $sequence2 tests if any element in $sequence1 has an equal element in $sequence2. As this semantically already supports sequences of arbitrary length, no atomization must be applied.
Why?
The difference comes from the requirements imposed by the operators' signatures. If you compare sequences of arbitrary length in a set-based manner, there is no reason to include any special cases for empty sequences -- if an empty sequence is included, the comparison is automatically false by definition.
For the operators comparing single values, one has to consider the case where an empty sequence is passed; the decision was to not raise an error, but also return a value equal to false: the empty sequence. This allows to use the empty sequence as a kind of null value, when the value is unknown; anything compared to an unknown value can never be true, but must not (necessarily) be false. If you need to, you could check for an empty(...) result, if so, one of the values to be compared was unknown; otherwise they're simply different. In Java and other languages, a null value would have been used to achieve similar results, in Haskell there's the Data.Maybe.

What's the difference between `=` and `<-` in R? [duplicate]

This question already has answers here:
What are the differences between "=" and "<-" assignment operators?
(9 answers)
Closed 3 years ago.
I'm using R 2.8.1 and it is possible to use both = and <- as variable assignment operators. What's the difference between them? Which one should I use?
From here:
The operators <- and = assign into the environment in which they are evaluated. The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.
Reading from "Introducing Monte Carlo Methods with R", by Robert and Casella:
"The assignment operator is =, not to be confused with ==, which is the Boolean operator for equality. An older assignment operator is <- and, for compatibility reasons, it still remains functional, but it should be ignored to ensure cleaner programming.
(As pointed out by Spector, P. (2009). 'Data Manipulation with R' - Section 8.7., an exception is when using system.time, since = is then used to identify keywords)
A misleading feature of the assignment operator <- is found in Boolean
expressions such as
> if (x[1]<-2) ...
which is supposed to test whether or not x[1] is less than -2 but ends
up allocating 2 to x[1], erasing its current value! Note also that using
> if (x[1]=-2) ...
mistakenly instead of (x[1]==-2) has the same consequence."

Resources