使用if-else语句有条件地定义`R`中的函数

时间:2012-04-03 15:04:08

标签: r

R中,我根据先前设置的参数值定义函数lengths

if(condition == 1){
    lengths <- function(vector) {
        n <- ceiling(length(vector)/2)
    }
}
else if(condition == 2){
    lengths <- function(vector) {
        n <- length(vector)
    }
}
else if(condition == 3){
    lengths <- function(vector) {
        n <- length(vector)*2
    }
}
else{
    lengths <- function(vector) {
        n <- length(vector)+10
    }
}

以这种方式有条件地定义一个函数似乎有点......凌乱。还有更好的方法吗?

2 个答案:

答案 0 :(得分:9)

您可以使用switch

lengths <- function(vector, condition) {
  switch(condition,
    ceiling(length(vector)/2),
    length(vector),
    length(vector)*2,
    length(vector)*+10)
}

此函数提供的行为更像您的示例代码:

lengths <- function(vector, condition) {
  switch(as.character(condition),
    `1`=ceiling(length(vector)/2),
    `2`=length(vector),
    `3`=length(vector)*2,
    length(vector)*+10)
}

...此函数将由condition

的值定义
condition <- 1
lengths <- switch(as.character(condition), 
    `1`=function(vector) ceiling(length(vector)/2),
    `2`=function(vector) length(vector),
    `3`=function(vector) length(vector)*2,
    function(vector) length(vector)*+10)
lengths
# function(vector) ceiling(length(vector)/2)

答案 1 :(得分:0)

基于CSGillespie建议的快速黑客攻击:

length.lut  <-  cbind(c(0.5,1,2,1,),c(0,0,0,10))

lengths <- function(vector, condition) vector*length.lut[condition,1] + length.lut[condition,2]