r - & 和 &&, | 有什么区别和 ||在 R 中?

标签 r

为什么有四个逻辑运算符:

&, &&
|, ||

使用上有什么区别?

是的,我已经检查过文档,但我有点困惑。文档说:

 ‘&’ 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.

我认为一个例子可以清楚地展示它们。谢谢。

最佳答案

主要区别如下...

  1. 长格式(&& 或 ||)短路,这意味着它是否可以通过仅验证第一个元素来识别结果。在执行 && 时,如果前两个元素的比较结果为 false,则比较下一组元素也将导致 False。所以,它返回 false。在做||时如果前几个元素的比较结果为 true,我们可以自信地说任何进一步的验证都不会改变结果,因此它返回 True

  2. 简短形式继续对整个向量进行操作,并创建一个结果向量并返回它。

希望这有帮助。

& 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/

相关文章:

r - 如何从R中的url地址直接读取图像文件

r - 如何确认两个R对象具有相同的结构?

r - diff() 在动物园对象上失败

R 在data.table(或ddply)中动态构建 "list"

r - 如何在不使用 ifelse 的情况下基于范围创建因子列?

r - 控制主要网格线的长度 - ggplot2

r - 如何在 R Shiny 和 plotly 中处理大量数据?

r - 如何制表多个数据文件的均值

r - 如何在一列内有条件地计数(对于所有行)并循环遍历所有列以在 R 中创建列联表

r - 填充曲线下不与任何其他曲线重叠的区域