R中AND和OR逻辑运算符的短形式(&,|)和长形式(&& ;, ||)之间有什么区别? [英] What is the difference between short (&,|) and long (&&, ||) forms of AND, OR logical operators in R?
问题描述
可能重复:
R:链接条件应为&不是&&
Possible Duplicate:
R: subset() logical-and operator for chaining conditions should be & not &&
R中AND或OR逻辑运算符的短(&
,|
)和长(&&
,||
)形式之间有什么区别?
What is the difference between short (&
,|
) and long (&&
, ||
) forms of AND, OR logical operators in R?
例如:
-
x==0 & y==1
-
x==0 && y==1
-
x==0 | y==1
-
x==0 || y==1
x==0 & y==1
x==0 && y==1
x==0 | y==1
x==0 || y==1
我总是在代码中使用缩写形式.有障碍吗?
I always use the short forms in my code. Does it have any handicaps?
推荐答案
&
和|
-是元素方式的,可以与矢量运算配合使用,而||
和&&
始终生成单个TRUE
或FALSE
&
and |
- are element-wise and can be used with vector operations, whereas, ||
and &&
always generate single TRUE
or FALSE
区别:
> x <- 1:5
> y <- 5:1
> (x > 2) & (y < 3)
[1] FALSE FALSE FALSE TRUE TRUE
> (x > 2) && (y < 3) # here operaand && takes only 1'st elements from logical
# vectors (x>2) and (y<3)
> FALSE
因此,&&
和||
通常在if (condition) state_1 else state_2
语句中使用,如下
处理长度为1
So, &&
and ||
are commonly used in if (condition) state_1 else state_2
statements, as
dealing with vectors of length 1
这篇关于R中AND和OR逻辑运算符的短形式(&,|)和长形式(&& ;, ||)之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!