如何在 R 函数中使用 switch 语句? [英] How to use the switch statement in R functions?

查看:37
本文介绍了如何在 R 函数中使用 switch 语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to use for my function in R the statement switch() to trigger different computation according to the value of the function's argument.

例如,在 Matlab 中,您可以通过编写

For instance, in Matlab you can do that by writing

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

我发现这篇文章 - switch() 语句用法 - 解释了如何使用 switch,但对我没有真正的帮助,因为我想执行更复杂的计算(矩阵运算)而不是简单的 mean.

I found this post - switch() statement usage - that explain how to use switch, but not really helpful to me as I want to perform more sophisticated computation (matrix operations) and not a simple mean.

推荐答案

嗯,switch 可能并不是真的要这样工作,但你可以:

Well, switch probably wasn't really meant to work like this, but you can:

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

...每个 case 都是一个表达式——通常只是一个简单的事情,但在这里我使用了一个卷曲块,这样你就可以在那里填充你想要的任何代码......

...each case is an expression - usually just a simple thing, but here I use a curly-block so that you can stuff whatever code you want in there...

这篇关于如何在 R 函数中使用 switch 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆