最近在使用R语言进行数据探索时,发现逻辑操作 & 和 && 代表的是两种逻辑操作,这里整理一下R中的逻辑操作符,以下是Qucik-R的操作符介绍:

Operators

R’s binary and logical operators will look very familiar to programmers. Note that binary operators work on vectors and matrices as well as scalars.

Arithmetic Operators

1
2
3
4
5
6
7
8
Operator Description
+ addition
- subtraction
* multiplication
/ division
^ or ** exponentiation
x %% y modulus (x mod y) 5%%2 is 1
x %/% y integer division 5%/%2 is 2

Logical Operators

1
2
3
4
5
6
7
8
9
10
11
Operator Description
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== exactly equal to
!= not equal to
!x Not x
x | y x OR y
x & y x AND y
isTRUE(x) test if X is TRUE

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# An example
x <- c(1:10)
x[(x>8) | (x<5)]
# yields 1 2 3 4 9 10
# How it works
x <- c(1:10)
x
1 2 3 4 5 6 7 8 9 10
x > 8
F F F F F F F F T T
x < 5
T T T T F F F F F F
x > 8 | x < 5
T T T T F F F F T T
x[c(T,T,T,T,F,F,F,F,T,T)]
1 2 3 4 9 10

&与&&,|与||区别

&和|称为短逻辑符,&&及||称为长逻辑符,长逻辑符只比较左边和右边的第一个元素,而短逻辑符会比较所有元素。通过示例来看:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
> a<-c(TRUE, FALSE, TRUE, FALSE)
> b<-c(FALSE, FALSE, TRUE, TRUE)
> c<-c(TRUE, FALSE, FALSE, FALSE)
> a & b
[1] FALSE FALSE TRUE FALSE
> a && b
[1] FALSE
> a & c
[1] TRUE FALSE FALSE FALSE
> a && c
[1] TRUE
> a | b
[1] TRUE FALSE TRUE TRUE
> a || b
[1] TRUE
> a | c
[1] TRUE FALSE TRUE FALSE
> a || c
[1] TRUE