【发布时间】:2013-06-19 15:03:43
【问题描述】:
为什么我们可以在with() 或within() 语句中使用ifelse() 而不是else if(){}?
我听说第一个是可矢量化的,而不是后者。什么意思?
【问题讨论】:
标签: r vector if-statement
为什么我们可以在with() 或within() 语句中使用ifelse() 而不是else if(){}?
我听说第一个是可矢量化的,而不是后者。什么意思?
【问题讨论】:
标签: r vector if-statement
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 中使用&& 或||。
【讨论】:
第二部分的答案:
*当 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
【讨论】: