如何使 if 返回预期结果 (R)?



关于如何解决此错误的任何想法?

Warning messages:
1: In if (A <0) {:
the condition has length> 1 and only the first element will be used
2: In if (A> 0) {:
the condition has length> 1 and only the first element will be used
A <- c (0, -2, -4,1,5)
B <- if (A <0) {A/-2} else if (A> 0) {A/2} else {A = 0}

呵呵: B 的结果必须是 (0,1,2,0,5,2.5)。

您的问题的答案是使用ifelse而不是ififelse用于向量,而if/else用于标量。

A <- c (0, -2, -4,1,5)
ifelse(A < 0, A/-2, ifelse(A> 0,  A/2, 0))
#[1] 0.0 1.0 2.0 0.5 2.5

但是,您在这里也不需要ifelse,因为这可以简化为:

abs(A/2)
#[1] 0.0 1.0 2.0 0.5 2.5

相关内容

最新更新