根据R语言的定义,&和&&(对应|和||)的区别在于前者是向量化的,而后者不是。

根据帮助文本,我读到的差异类似于“And”和“AndAlso”之间的差异(相应的“Or”和“OrElse”)… 意义: 不是所有的评估,如果它们不需要(例如,如果A为真,A或B或C总是为真,所以如果A为真,就停止评估)

有人能在这里照亮吗? 还有,R里有AndAlso和OrElse吗?


&&和||是所谓的“短路”。这意味着如果第一个操作数足以确定表达式的值,则它们将不计算第二个操作数。

例如,如果&&的第一个操作数为假,那么对第二个操作数求值就没有意义了,因为它不能改变表达式的值(false && true和false && false都为假)。当第一个操作数为真时,||也是如此。

你可以在这里阅读更多信息:http://en.wikipedia.org/wiki/Short-circuit_evaluation从该页的表格中,你可以看到&&在VB中等价于AndAlso。NET,我想你指的是。

较短的是向量化的,这意味着它们可以返回一个向量,像这样:

((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE  TRUE FALSE FALSE

较长的形式从左到右求值,只检查每个向量的第一个元素,因此上面给出

((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE

正如帮助页所说,这使得较长的形式“适合于编程控制流,并且通常在if子句中更受欢迎。”

所以只有当你确定向量的长度为1时你才会使用长形式。

你应该绝对确定你的向量长度只有1,比如它们是只返回长度为1的布尔值的函数。如果向量的长度可能是>1,你要用简写形式。所以如果你不是绝对确定,你应该先检查,或者使用简短的形式,然后使用all和any将它减少到长度为1的控制流语句中使用,比如if。

函数all和any通常分别用于向量化比较的结果,以判断所有比较或任何比较是否为真。这些函数的结果肯定是长度为1的,因此适合在if子句中使用,而向量化比较的结果则不适合。(尽管这些结果适用于ifelse。

最后一个区别是:&&和||只计算它们需要计算的项(这似乎就是短路的意思)。例如,这里有一个使用未定义值a的比较;如果它没有短路,就像&和|一样,它会给出一个错误。

a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found

最后,参见《地狱之R》的8.2.17节,标题为“andand and”。

The answer about "short-circuiting" is potentially misleading, but has some truth (see below). In the R/S language, && and || only evaluate the first element in the first argument. All other elements in a vector or list are ignored regardless of the first ones value. Those operators are designed to work with the if (cond) {} else{} construction and to direct program control rather than construct new vectors.. The & and the | operators are designed to work on vectors, so they will be applied "in parallel", so to speak, along the length of the longest argument. Both vectors need to be evaluated before the comparisons are made. If the vectors are not the same length, then recycling of the shorter argument is performed.

当对&&或||的参数求值时,存在“短路”,因为如果从左到右连续的任何值是确定的,则求值将停止并返回最终值。

> if( print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(FALSE && print(1) ) {print(2)} else {print(3)} # `print(1)` not evaluated
[1] 3
> if(TRUE && print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(TRUE && !print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 3
> if(FALSE && !print(1) ) {print(2)} else {print(3)}
[1] 3

短路的优势只有在论证需要很长时间来评估时才会显现出来。当参数是处理较大对象或具有更复杂的数学操作的函数时,通常会发生这种情况。

更新:最新版本的新闻(“R”)说,向&&或||提供长度大于1的向量已被弃用,并发出警告,RCore的目的是让它在R的后续版本中成为一个错误。