2012-05-01 32 views
57

我想用我的函数R语句switch()根据函数参数的值触发不同的计算。如何在R函数中使用switch语句?

例如,在Matlab你可以做到这一点通过写

switch(AA)   
case '1' 
... 
case '2' 
... 
case '3' 
... 
end 

我发现这个职位 - switch() statement usage - 解释如何使用switch,但不是真的对我很有帮助,因为我要执行更复杂的计算(矩阵运算)而不是简单的mean

回答

75

好,switch可能不是真正的意思是这样的工作,但你可以:

AA = 'foo' 
switch(AA, 
foo={ 
    # case 'foo' here... 
    print('foo') 
}, 
bar={ 
    # case 'bar' here... 
    print('bar')  
}, 
{ 
    print('default') 
} 
) 

...每一种情况下是一种表达 - 通常只是一个简单的事情,但在这里我用卷曲 - 阻止,以便你可以填充任何你想要的代码在那里...

+4

是有办法做到这一点没有比较字符串?这似乎广泛低效。 – Julius

30

我希望这个例子有所帮助。你可以使用花括号来确保你已经把所有的东西都放在切换器变换器中(抱歉,不知道技术术语,但是在=号之前的术语会改变发生的事情)。我认为开关是一种更受控制的if() {} else {}陈述。

每次开关功能相同,但我们提供的命令发生变化。

do.this <- "T1" 

switch(do.this, 
    T1={X <- t(mtcars) 
     colSums(mtcars)%*%X 
    }, 
    T2={X <- colMeans(mtcars) 
     outer(X, X) 
    }, 
    stop("Enter something that switches me!") 
) 
######################################################### 
do.this <- "T2" 

switch(do.this, 
    T1={X <- t(mtcars) 
     colSums(mtcars)%*%X 
    }, 
    T2={X <- colMeans(mtcars) 
     outer(X, X) 
    }, 
    stop("Enter something that switches me!") 
) 
######################################################## 
do.this <- "T3" 

switch(do.this, 
    T1={X <- t(mtcars) 
     colSums(mtcars)%*%X 
    }, 
    T2={X <- colMeans(mtcars) 
     outer(X, X) 
    }, 
    stop("Enter something that switches me!") 
) 

这是一个函数内部:

FUN <- function(df, do.this){ 
    switch(do.this, 
     T1={X <- t(df) 
      P <- colSums(df)%*%X 
     }, 
     T2={X <- colMeans(df) 
      P <- outer(X, X) 
     }, 
     stop("Enter something that switches me!") 
    ) 
    return(P) 
} 

FUN(mtcars, "T1") 
FUN(mtcars, "T2") 
FUN(mtcars, "T3") 
26

开关的那些不同的方式...

# by index 
switch(1, "one", "two") 
## [1] "one" 


# by index with complex expressions 
switch(2, {"one"}, {"two"}) 
## [1] "two" 


# by index with complex named expression 
switch(1, foo={"one"}, bar={"two"}) 
## [1] "one" 


# by name with complex named expression 
switch("bar", foo={"one"}, bar={"two"}) 
## [1] "two"