为什么有四个逻辑运算符:
&, &&
|, ||
Run Code Online (Sandbox Code Playgroud)
使用上有什么不同?
是的,我检查了文档,但我有点困惑.文档说:
‘&’ 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.
Run Code Online (Sandbox Code Playgroud)
我认为一个例子将清楚地展示它们.谢谢.
Bud*_*dha 23
主要差异如下......
长形式(&&或||)短路,这意味着它只能通过验证第一个元素来识别结果.在做&&时,如果前两个元素的比较导致错误,那么比较下一组元素也会导致False
.所以,它返回false.在做|| 如果比较在前几个元素中得到真实,我们可以自信地说任何进一步的验证都不会改变结果,所以它返回True
.
简短形式继续为整个向量做,并创建结果向量并返回它.
希望这可以帮助.
&和&&表示逻辑AND和| 和|| 表示逻辑OR.较短的形式以与算术运算符大致相同的方式执行元素比较.较长的形式从左到右评估仅检查每个向量的第一个元素.评估仅在确定结果之前进行.较长的形式适用于编程控制流程,通常在if子句中是优选的.
资料来源:http://stat.ethz.ch/R-manual/R-patched/library/base/html/Logic.html