R陷阱:用于组合条件的逻辑和运算符为&.不是&& [英] R gotcha: logical-and operator for combining conditions is & not &&

查看:62
本文介绍了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.

这篇关于R陷阱:用于组合条件的逻辑和运算符为&amp;.不是&amp;&amp;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆