2013-06-22 84 views
5

为什么我们可以用ifelse()而不是else if(){}with()within()声明?else if(){} VS ifelse()

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

回答

11

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通常是有用的。

9

回答你的第二个部分:

* 使用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 

使用ifelse当x有长度为1但y的长度大于1

ifelse (x < y,x,y) 
[1] 4 4 4 3 4 
+0

这是超级有趣。我可能会认为它是一个缺点,如果我试图比较一个int和列表,我更喜欢得到一个警告 –