为什么有四个逻辑运算符:
&, &&
|, ||
使用上有什么区别?
是的,我已经检查过文档,但我有点困惑。文档说:
‘&’ 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.
我认为一个例子可以清楚地展示它们。谢谢。
最佳答案
主要区别如下...
长格式(&& 或 ||)短路,这意味着它是否可以通过仅验证第一个元素来识别结果。在执行 && 时,如果前两个元素的比较结果为 false,则比较下一组元素也将导致
False
。所以,它返回 false。在做||时如果前几个元素的比较结果为 true,我们可以自信地说任何进一步的验证都不会改变结果,因此它返回True
。简短形式继续对整个向量进行操作,并创建一个结果向量并返回它。
希望这有帮助。
& 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.
来源:http://stat.ethz.ch/R-manual/R-patched/library/base/html/Logic.html
关于r - & 和 &&, | 有什么区别和 ||在 R 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16027840/