【问题标题】:else if(){} VS ifelse()否则 if(){} VS ifelse()
【发布时间】:2013-06-19 15:03:43
【问题描述】:

为什么我们可以在with()within() 语句中使用ifelse() 而不是else if(){}

我听说第一个是可矢量化的,而不是后者。什么意思?

【问题讨论】:

    标签: r vector if-statement


    【解决方案1】:

    if 构造仅在将向量传递给它时考虑第一个组件,(并给出警告)

    if(sample(100,10)>50) 
        print("first component greater 50") 
    else 
        print("first component less/equal 50")
    

    ifelse 函数对每个分量进行检查并返回一个向量

    ifelse(sample(100,10)>50, "greater 50", "less/equal 50")
    

    例如,ifelse 函数对transform 很有用。它通常是有用的 在ifelse 条件中使用&|,在if 中使用&&||

    【讨论】:

      【解决方案2】:

      第二部分的答案:

      *当 x 的长度为 1 但 y 的长度大于 1 时使用 if *

       x <- 4
       y <- c(8, 10, 12, 3, 17)
      if (x < y) x else y
      
      [1]  8 10 12  3 17
      Warning message:
      In if (x < y) x else y :
        the condition has length > 1 and only the first element will be used
      

      当 x 的长度为 1 但 y 的长度大于 1 时使用ifelse

      ifelse (x < y,x,y)
      [1] 4 4 4 3 4
      

      【讨论】:

      • 这非常有趣。我实际上可能认为这是一个劣势,如果我尝试比较一个 int 和 list,我宁愿得到一个警告
      猜你喜欢
      • 2021-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-23
      相关资源
      最近更新 更多