那么,“条件或”(也称为“短路或”)如何写成||
运算符(operator)在 R 中工作?
查询 ?Logic
显示:
& 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.
听起来很标准。
> library(dplyr)
> as_tibble(mtcars) %>% filter(between(hp,50,70))
# A tibble: 5 x 11
mpg cyl disp hp drat wt qsec vs am gear carb
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 24.4 4 147. 62 3.69 3.19 20 1 0 4 2
2 32.4 4 78.7 66 4.08 2.2 19.5 1 1 4 1
3 30.4 4 75.7 52 4.93 1.62 18.5 1 1 4 2
4 33.9 4 71.1 65 4.22 1.84 19.9 1 1 4 1
5 27.3 4 79 66 4.08 1.94 18.9 1 1 4 1
好的。
> as_tibble(mtcars) %>% filter(between(hp,80,90))
# A tibble: 0 x 11
# … with 11 variables: mpg <dbl>, cyl <dbl>, disp <dbl>, hp <dbl>, drat <dbl>, ...
# carb <dbl>
好的。让我们试试标准或
|
,这相当于在这里设置联合:> as_tibble(mtcars) %>% filter(between(hp,50,70) | between(hp,80,90))
# A tibble: 5 x 11
mpg cyl disp hp drat wt qsec vs am gear carb
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 24.4 4 147. 62 3.69 3.19 20 1 0 4 2
2 32.4 4 78.7 66 4.08 2.2 19.5 1 1 4 1
3 30.4 4 75.7 52 4.93 1.62 18.5 1 1 4 2
4 33.9 4 71.1 65 4.22 1.84 19.9 1 1 4 1
5 27.3 4 79 66 4.08 1.94 18.9 1 1 4 1
好的。让我们试试条件或
||
, 应该给出相同的结果( ||
不应该改变语义,只改变计算效率,除了偏函数等的边界情况):> as_tibble(mtcars) %>% filter(between(hp,50,70) || between(hp,80,90))
# A tibble: 0 x 11
# … with 11 variables: mpg <dbl>, cyl <dbl>, disp <dbl>, hp <dbl>, drat <dbl>, ...
# carb <dbl>
这是什么怪事?
between(hp,50,70) || between(hp,80,90)
无处产生 TRUE?
最佳答案
||
运算符只比较向量的第一个元素,并返回单个逻辑结果,而 |
按元素比较向量,并返回向量结果。见,例如:
x <- c(FALSE, TRUE)
y <- c(FALSE, FALSE)
x | y
#> [1] FALSE TRUE
x || y
#> [1] FALSE
您引用的帮助文本中实际上也提到了这一点:“较长的形式从左到右计算仅检查每个向量的第一个元素。” [强调]
创建于 2019-10-15 由 reprex package (v0.3.0)
关于r - 写为 "conditional or"运算符的 "short-circuit or"(也称为 `||` )如何在 R 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58391559/