【问题标题】:Vectorized IF statement combined with logic AND in R向量化的 IF 语句与 R 中的逻辑 AND 相结合
【发布时间】:2020-03-17 07:16:41
【问题描述】:

这是我希望拥有的代码:

a=1
b=c(2,1.5,0.7)

if (a==1 & b<1) {

     b=1   # but here's the problem, that only the first value of the vector b is considered

}  # end if loop

print(b)

好的,我也可以这样写代码,但我希望能在你的帮助下阻止它。

a=1
b=c(2,1.5,0.7)

if (a==1) {

     for (i in 1:length(b)) {

          if (b[i]<1) {

               b[i]=1  

          }  # end if loop

     }  # end for loop 

}  # end if loop

print(b)

我也发现了这个问题Vectorized IF statement in R?,但我无法将其转移到我的问题中......

提前感谢您的帮助。

【问题讨论】:

  • 这是你要找的as.integer(a == 1 &amp; b &lt; 1)吗?
  • if (a==1) b &lt;- pmax(b, 1)
  • 顺便说一句 if 不是循环。正确你可以写# end of the then-block
  • @jogo:这正是我想要的。非常感谢。
  • @tmfmnk:当我把它放在我的 if 语句中时,条件的长度大于 1,但只使用向量 b 的第一个元素。所以问题仍然存在 - 我希望我正确解释了您的评论。

标签: r if-statement logic vectorization


【解决方案1】:
b <- ifelse(a==1 & b<1, 1, b)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 2016-07-29
    相关资源
    最近更新 更多