【发布时间】:2011-08-31 08:43:31
【问题描述】:
我正在编写一个 R 函数,它变得非常大。它承认多项选择,我是这样组织的:
myfun <- function(y, type=c("aa", "bb", "cc", "dd" ... "zz")){
if (type == "aa") {
do something
- a lot of code here -
....
}
if (type == "bb") {
do something
- a lot of code here -
....
}
....
}
我有两个问题:
- 有没有更好的方法,以便对参数类型的每个选择不使用“if”语句?
- 为每个“类型”选择编写一个子函数是否更实用?
如果我写子函数,它会是这样的:
myfun <- function(y, type=c("aa", "bb", "cc", "dd" ... "zz")){
if (type == "aa") result <- sub_fun_aa(y)
if (type == "bb") result <- sub_fun_bb(y)
if (type == "cc") result <- sub_fun_cc(y)
if (type == "dd") result <- sub_fun_dd(y)
....
}
子函数当然是在别处定义的(在 myfun 的顶部,或以其他方式)。
我希望我的问题很清楚。提前致谢。
- 附加信息 -
我正在编写一个函数,将一些不同的过滤器应用于图像(不同的过滤器 = 不同的“类型”参数)。有些过滤器共享一些代码(例如,“aa”和“bb”是两个高斯过滤器,仅一行代码不同),而其他过滤器则完全不同。
所以我不得不使用很多 if 语句,即
if(type == "aa" | type == "bb"){
- do something common to aa and bb -
if(type == "aa"){
- do something aa-related -
}
if(type == "bb"){
- do something bb-related -
}
}
if(type == "cc" | type == "dd"){
- do something common to cc and dd -
if(type == "cc"){
- do something cc-related -
}
if(type == "dd"){
- do something dd-related -
}
}
if(type == "zz"){
- do something zz-related -
}
等等。 此外,代码中还有一些 if 语句“做某事”。 我正在寻找组织代码的最佳方式。
【问题讨论】:
-
如果一段代码至少可重复使用两次,我通常会“功能化”它。如果没有,您在
if语句中使用代码块的初始方法似乎是合理的。