【发布时间】: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 & b < 1)吗? -
if (a==1) b <- pmax(b, 1) -
顺便说一句
if不是循环。正确你可以写# end of the then-block -
@jogo:这正是我想要的。非常感谢。
-
@tmfmnk:当我把它放在我的 if 语句中时,条件的长度大于 1,但只使用向量 b 的第一个元素。所以问题仍然存在 - 我希望我正确解释了您的评论。
标签: r if-statement logic vectorization