else if(){} VS ifelse()

Wic*_*elo 8 if-statement r vector

为什么我们可以使用ifelse(),但不能else if(){}with()within()声明?

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

Kar*_* W. 13

if构建体仅考虑当载体被传递给它的第一组分,(并给出一个警告)

if(sample(100,10)>50) 
    print("first component greater 50") 
else 
    print("first component less/equal 50")
Run Code Online (Sandbox Code Playgroud)

ifelse函数对每个组件执行检查并返回一个向量

ifelse(sample(100,10)>50, "greater 50", "less/equal 50")
Run Code Online (Sandbox Code Playgroud)

例如,该ifelse功能非常有用transform.使用&|ifelse条件和/ &&||中使用它通常很有用if.


Met*_*ics 10

回答你的第二部分:

*使用if当x具有1长度但y分别为大于1*

 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
Run Code Online (Sandbox Code Playgroud)

使用ifelse当x具有1长度但y分别为大于1

ifelse (x < y,x,y)
[1] 4 4 4 3 4
Run Code Online (Sandbox Code Playgroud)