R陷阱:用于组合条件的逻辑和运算符为&.不是&&
问题描述:
为什么subset()
不能与结合两个条件的逻辑和&&
运算符一起使用?
Why doesn't subset()
work with a logical and &&
operator combining two conditions?
> subset(tt, (customer_id==177 && visit_date=="2010-08-26"))
<0 rows> (or 0-length row.names)
但它们各自独立工作:
> subset(tt, customer_id==177)
> subset(tt, visit_date=="2010-08-26")
(想要避免使用较大的临时变量-我的数据集很大)
(Want to avoid using large temporary variables - my dataset is huge)
答
从Logical Operators
的帮助页面,可通过?"&&"
访问:
From the help page for Logical Operators
, accessible by ?"&&"
:
&和&&表示逻辑AND和|和||表示逻辑或.较短的形式以与算术运算符几乎相同的方式执行元素比较.较长的形式从左到右求值,仅检查每个向量的第一个元素.评估仅进行到确定结果为止.较长的形式适合于编程控制流,通常是if子句中首选的形式.
(R版本2.13-0)
换句话说,当使用subset
时,请使用单个&
.
In other words, when using subset
, use the single &
.
以下是区别的说明:
c(1,1,0,0) & c(1,0,1,0)
[1] TRUE FALSE FALSE FALSE
c(1,1,0,0) && c(1,0,1,0)
[1] TRUE
如果与其他编程范例相比,这看起来很古怪,请记住R需要提供矢量化形式的运算符.
If this looks quirky compared to other programming paradigms, remember that R needs to provide a vectorised form of the operator.