# 逻辑运算的操纵
## 逻辑/布尔运算符
| **Logical operator in R** | **Description** |
|:-------------------------:|:---------------------------------------------------:|
| & | Elementwise logical ‘AND’ |
| && | Vector logical ‘AND’ |
| \| | Elementwise logical ‘OR’ |
| \|\| | Vector logical ‘OR’ |
| ! | Logical negation ‘NOT’ |
| xor() | Elementwise exclusive ‘OR’ equivalent to !( x \| y) |
![](images/boolean_operations.png){fig-align="center" width="75%"}
```{r}
40 & 5 > 30 # FALSE
40 | 5 > 30 # TRUE
!TRUE # FALSE
!FALSE # TRUE
#---------
# Vectors
#---------
x <- c(3, 4, 5)
y <- c(3, 5, 1)
x & y # TRUE TRUE TRUE
#x && y # TRUE error
x | y # TRUE TRUE TRUE
#x || y # TRUE error
!x # FALSE FALSE FALSE
xor(x, y) # FALSE FALSE FALSE
```
```{r}
(x1 <- 1:10 %% 2 == 0)
(y1 <- 1:10 %% 5 == 0)
(x2 <- which(x1))
(y2 <- which(y1))
# 交集
x1 & y1
base::intersect(x2, y2)
# 并集
x1 | y1
base::union(x2,y2)
# 差集
x1 & !y1
base::setdiff(x2, y2)
# 只有一个为真
xor(x1, y1)
base::setdiff(base::union(x2, y2), base::intersect(x2, y2))
```
### 缺失值
```{r}
df <- tibble(x = c(TRUE, FALSE, NA))
df |>
mutate(
and = x & NA, # A & B A为TRUE,返回B ;A为FALSE,返回A
or = x | NA # A | B A为TRUE,返回A ;A为FALSE,返回B
)
```
## 关系运算符
| **Relational operator in R** | **Description** |
|:----------------------------:|:---------------------:|
| \> | Greater than |
| \< | Lower than |
| \>= | Greater or equal than |
| \<= | Lower or equal than |
| == | Equal to |
| != | Not equal to |
## 逻辑比较
### 浮点比较
```{r}
x <- c(1 / 49 * 49, sqrt(2) ^ 2)
x
x == c(1, 2)
print(x, digits = 16)
near(x, c(1, 2))
```
### 缺失值
```{r}
# “contagious”
NA == NA
is.na(c(TRUE, NA, FALSE))
```
## `%in%`
```{r}
1:12 %in% c(1, 5, 11)
c(1, 2, NA) %in% NA
```
## 条件转换
### **`if_else()`**
```{r}
x <- c(-3:3, NA)
if_else(x > 0, "+ve", "-ve", missing = "???")
if_else(x == 0,
"0",
if_else(x < 0, "-ve", "+ve"), "???")
```
```{r}
x1 <- c(NA, 1, 2, NA)
y1 <- c(3, NA, 4, 6)
if_else(is.na(x1), y1, x1)
```
### **`case_when()`**
```{r}
x <- c(-3:3, NA)
case_when(
x == 0 ~ "0",
x < 0 ~ "-ve",
x > 0 ~ "+ve",
is.na(x) ~ "???"
)
```
## 逻辑汇总
```{r}
x<-c(2,3,5,1,4)
x>2
# 所有
all(x>2)
# 存在
any(x>2)
```