R Conditional && || & |

在R中有4种逻辑符号,&&, ||, &, |

其中&, |是判断向量中单个元素的,返回的也是多个布尔元素的向量。

而&&和||是判断整个向量的,返回单个布尔逻辑值。

例子:

> x <- 1:5
> y <- c(2,2,2,2,4)
> x>1
[1] FALSE  TRUE  TRUE  TRUE  TRUE
> y>2
[1] FALSE FALSE FALSE FALSE  TRUE
> x>1 | y>2
[1] FALSE  TRUE  TRUE  TRUE  TRUE
> x>1 & y>2
[1] FALSE FALSE FALSE FALSE  TRUE

以下用法基本用不上,你甚至可能觉得返回结果有点奇怪,其实只使用第一个逻辑值的结果:

> x>1 && y>2
[1] FALSE
> x>1 || y>2
[1] FALSE

> x>1
[1] FALSE  TRUE  TRUE  TRUE  TRUE
> x>=1
[1] TRUE TRUE TRUE TRUE TRUE
> x>1 && x>=1
[1] FALSE
> x>1 || x>=1   # 这里只用了第一个逻辑值的结果作为整个表达式的结果
[1] TRUE

常用的条件判断

ifelse(condition, a, b) returns a vector of the length of its longest argument, with elements a[i] if condition[i] is true, otherwise b[i].

如果a,b的长度小于condition的长度,则循环返回。

> x>1
[1] FALSE  TRUE  TRUE  TRUE  TRUE
> ifelse(x>1,a,b)
[1] 10  2  1  2  1

这里需要注意,condition[i]和a[i],b[i]是对应的,所以有位置关系。

> ifelse(x>1 && x>1,a,b)
[1] 10

以上返回b[1]

另一种用法是在if else表达式中。

数字0表示false, 非0表示true, 这个和ifelse(condition,a,b)用法不一样,请注意,条件中只能是长度为1的布尔逻辑值,否则只使用第一个逻辑值。

> if (0) a else b

[1] 10 11 12 13 14 15

> if (1) a else b

[1] 1 2

> if (10) a else b

[1] 1 2

使用第一个逻辑值:

> if (c(10,0)) a else b

[1] 1 2

Warning message:

In if (c(10, 0)) a else b :

  the condition has length > 1 and only the first element will be used

[参考]
1. http://cran.r-project.org/doc/manuals/r-release/R-intro.html#Loops-and-conditional-execution

2. > help("&&")

Logic                   package:base                   R Documentation

Logical Operators

Description:

     These operators act on raw, logical and number-like vectors.

Usage:

     ! x
     x & y
     x && y
     x | y
     x || y
     xor(x, y)

     isTRUE(x)

Arguments:

    x, y: raw or logical or ‘number-like’ vectors (i.e., of types
          ‘double’ (class ‘numeric’), ‘integer’ and ‘complex’)), or
          objects for which methods have been written.

Details:

     ‘!’ indicates logical negation (NOT).

     ‘&’ 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.

     ‘xor’ indicates elementwise exclusive OR.

     ‘isTRUE(x)’ is an abbreviation of ‘identical(TRUE, x)’, and so is
     true if and only if ‘x’ is a length-one logical vector whose only
     element is ‘TRUE’ and which has no attributes (not even names).

     Numeric and complex vectors will be coerced to logical values,
     with zero being false and all non-zero values being true.  Raw
     vectors are handled without any coercion for ‘!’, ‘&’, ‘|’ and
     ‘xor’, with these operators being applied bitwise (so ‘!’ is the
     1s-complement).

     The operators ‘!’, ‘&’ and ‘|’ are generic functions: methods can
     be written for them individually or via the ‘Ops’ (or S4 ‘Logic’,
     see below) group generic function.  (See ‘Ops’ for how dispatch is
     computed.)

     ‘NA’ is a valid logical object.  Where a component of ‘x’ or ‘y’
     is ‘NA’, the result will be ‘NA’ if the outcome is ambiguous.  In
     other words ‘NA & TRUE’ evaluates to ‘NA’, but ‘NA & FALSE’
     evaluates to ‘FALSE’.  See the examples below.

     See Syntax for the precedence of these operators: unlike many
     other languages (including S) the AND and OR operators do not have
     the same precedence (the AND operators have higher precedence than
     the OR operators).

Value:

     For ‘!’, a logical or raw vector(for raw ‘x’) of the same length
     as ‘x’: names, dims and dimnames are copied from ‘x’, and all
     other attributes (including class) if no coercion is done.

     For ‘|’, ‘&’ and ‘xor’ a logical or raw vector. The elements of
     shorter vectors are recycled as necessary (with a ‘warning’ when
     they are recycled only _fractionally_).  The rules for determining
     the attributes of the result are rather complicated.  Most
     attributes are taken from the longer argument, the first if they
     are of the same length.  Names will be copied from the first if it
     is the same length as the answer, otherwise from the second if
     that is.  For time series, these operations are allowed only if
     the series are compatible, when the class and ‘tsp’ attribute of
     whichever is a time series (the same, if both are) are used.  For
     arrays (and an array result) the dimensions and dimnames are taken
     from first argument if it is an array, otherwise the second.

     For ‘||’, ‘&&’ and ‘isTRUE’, a length-one logical vector.

S4 methods:

     ‘!’, ‘&’ and ‘|’ are S4 generics, the latter two part of the
     ‘Logic’ group generic (and hence methods need argument names ‘e1,
     e2’).

Note:

     The elementwise operators are sometimes called as functions as
     e.g.  ‘`&`(x, y)’: see the description of how argument-matching is
     done in ‘Ops’.

References:

     Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) _The New S
     Language_.  Wadsworth & Brooks/Cole.

See Also:

     ‘TRUE’ or ‘logical’.

     ‘any’ and ‘all’ for OR and AND on many scalar arguments.

     ‘Syntax’ for operator precedence.

     ‘bitwAnd’ for bitwise versions for integer vectors.

Examples:
     y <- 1 + (x <- stats::rpois(50, lambda = 1.5) / 4 - 1)
     x[(x > 0) & (x < 1)]    # all x values between 0 and 1
     if (any(x == 0) || any(y == 0)) "zero encountered"

     ## construct truth tables :

     x <- c(NA, FALSE, TRUE)
     names(x) <- as.character(x)
     outer(x, x, "&") ## AND table
     outer(x, x, "|") ## OR  table
时间: 2024-09-20 13:19:15

R Conditional && || & |的相关文章

预测分析:R语言实现.

数据科学与工程技术丛书 预测分析:R语言实现 Mastering Predictive Analytics with R [希] 鲁伊·米格尔·福特(Rui Miguel Forte) 著 吴今朝 译 图书在版编目(CIP)数据 预测分析:R语言实现/(希)鲁伊·米格尔·福特(Rui Miguel Forte)著:吴今朝译. -北京:机械工业出版社,2016.10 (数据科学与工程技术丛书) 书名原文:Mastering Predictive Analytics with R ISBN 978-

预测分析:R语言实现导读

前 言 预测分析以及更一般意义上的数据科学当前正处于被追捧的热潮中,因为像垃圾邮件过滤.单词补全和推荐引擎这样的预测性技术已经被广泛运用于日常生活.这些技术现在不仅越来越被我们所熟悉,还赢得了我们的信任.在计算机处理能力和软件方面(例如R语言及其大量专用的扩展包)的发展产生了这样的局面:用户经过培训就可以使用这些工具,而无需具备统计学的高级学位,也不需要使用公司或大学实验室专用的硬件.技术的成熟度和基础软硬件的可用性结合起来,让很多该领域的从业者倍感兴奋,他们感到可以为自己的领域和业务设计一些能

《量化金融R语言高级教程》一第1章 时间序列分析

第1章 时间序列分析 量化金融R语言高级教程在本章中,我们探讨一些时间序列分析的高级方法以及如何通过R来实现.作为一门学科,时间序列分析已有数百部著作,内容非常广泛(我们会在本章末的阅读列表中,列出在理论与R编程两方面最重要的参考目录).我们责无旁贷地精心界定了本章的范围,专注于实证金融与量化交易中必不可少的重要主题.但是,在起始阶段我们必须强调,本章仅仅为时间序列分析的进一步研究奠定了基础. 我们之前曾经出版过一本图书--<量化金融R语言初级教程>(Introduction to R for

Attribute2Image --- Conditional Image Generation from Visual Attributes 论文笔记

  Attribute2Image --- Conditional Image Generation from Visual Attributes     Target: 本文提出一种根据属性生成图像的产生式模型 .  有了具体属性的协助,生成的图像更加真实,降低了采样的不确定性. 基于这个假设,本文提出一种学习框架,得到了基于属性的产生式模型. 1. Attribute-conditioned Generative Modeling of Images.  3.1 Base Model: Co

Win7提示“英特尔(R)快速存储技术未在运行”怎么办?

  故障现象: 英特尔(R)RST 服务是英特尔快速存储服务,即 intel rapidst,该程序为配备 SATA 磁盘的台式机.移动电脑和服务器平台系统提供更高的性能和可靠性.当使用一个或多个 SATA 磁盘时,可因性能提高及耗电降低而获益.使用多个磁盘时,可增强对磁盘故障时数据丢失的保护,安装 Intel 快速存储服务前需要于 BIOS 中开启 AHCI 模式.很多计算机用户在开机后会发现 Intel(R) Rapid 状态为英特尔(R)RST 服务未在运行,右键选择打开英特尔快速存储技术

Win7桌面右下角提示“英特尔(R)快速存储技术未在运行”怎么办?

  故障现象: 英特尔(R)RST 服务是英特尔快速存储服务,即 intel rapidst,该程序为配备 SATA 磁盘的台式机.移动电脑和服务器平台系统提供更高的性能和可靠性.当使用一个或多个 SATA 磁盘时,可因性能提高及耗电降低而获益.使用多个磁盘时,可增强对磁盘故障时数据丢失的保护,安装 Intel 快速存储服务前需要于 BIOS 中开启 AHCI 模式.很多计算机用户在开机后会发现 Intel(R) Rapid 状态为英特尔(R)RST 服务未在运行,右键选择打开英特尔快速存储技术

Win7提示“英特尔(R)快速存储技术未在运行”怎么办

    故障现象: 英特尔(R)RST 服务是英特尔快速存储服务,即 intel rapidst,该程序为配备 SATA 磁盘的台式机.移动电脑和服务器平台系统提供更高的性能和可靠性.当使用一个或多个 SATA 磁盘时,可因性能提高及耗电降低而获益.使用多个磁盘时,可增强对磁盘故障时数据丢失的保护,安装 Intel 快速存储服务前需要于 BIOS 中开启 AHCI 模式.很多计算机用户在开机后会发现 Intel(R) Rapid 状态为英特尔(R)RST 服务未在运行,右键选择打开英特尔快速存储

【shell 】syntax error in conditional expression

编写shell 脚本时遇见 syntax error in conditional expression 错误, #!/bin/bash # cleanup /var/log/message LOG_DIR=/var/log ROOT_DID=0 LINES=50 E_XCD=66 E_NOTROOT=67 if [[ "$UID" -ne "$ROOT_UID"]] then  echo "Must be root to run this script.

《R语言游戏数据分析与挖掘》一2.1 开发环境准备和快速入门

2.1 开发环境准备和快速入门 2.1.1 R语言简介 R语言的前身是S语言,S语言是由AT &T Bell实验室的Rick Becker.John Chambers和Allan Wilks开发的一种用来进行数据探索.统计分析.作图的解释型语言.最初S语言的实现版本主要是S-PLUS.S-PLUS是一个商业软件,它基于S语言,并由MathSoft公司的统计科学部进一步完善.而R语言最初由来自新西兰大学的Ross Ihaka和Robert Gentleman开发(由于他们的名字都以R开头,所以该软