【问题标题】:How to test for more than one conditional?如何测试多个条件?
【发布时间】:2012-11-02 13:20:14
【问题描述】:

假设我有一个变量y 和一个变量i

y<- c(TRUE, TRUE, TRUE)
i<- 0

假设我想为y 中的每个布尔条件测试以下 if 语句:

if (y) {
i<-1
}

我该怎么做?也就是说,如果y 中的每个布尔条件都是TRUE,我想要i = 1

如果 y&lt;- c(TRUE, FALSE,TRUE),那么我希望 if 语句计算为 FALSEi=0。有谁知道我会怎么做?目前我收到此警告消息:

Warning message:
In if (y) { :
  the condition has length > 1 and only the first element will be used.

我将如何测试变量 y 的每个布尔条件?

【问题讨论】:

    标签: r if-statement boolean


    【解决方案1】:

    详细说明@Dason 的答案,all() any() sum()which() 在处理逻辑向量时非常有用

    例子:

          vec1 <- c(T, T, F, T, F)
    
    >     all(vec1)   # Are all elements True
          [1] FALSE
    
    >     any(vec1)   # Are any True
          [1] TRUE
    
    >     sum(vec1)   # How many are True
          [1] 3
    
    >     which(vec1) # Which elements (by index) are True
          [1] 1 2 4
    
    >     which(!vec1) # Which elements (by index) are False
          [1] 3 5
    

    示例 2:

    vec2 <- c(T, T, T, T, T)
    
    all(vec2)     # TRUE
    any(vec2)     # TRUE
    sum(vec2)     # 5
    which(vec2)   # 1 2 3 4 5
    which(!vec2)  # integer(0)
    

    【讨论】:

      【解决方案2】:

      您正在寻找all 函数。

      > y <- c(T, T, T)
      > all(y)
      [1] TRUE
      > y <- c(T, T, F)
      > all(y)
      [1] FALSE
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-18
        相关资源
        最近更新 更多