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

dpl*_*net 7 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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Jos*_*ich 9

你可以使用switch:

lengths <- function(vector, condition) {
  switch(condition,
    ceiling(length(vector)/2),
    length(vector),
    length(vector)*2,
    length(vector)*+10)
}
Run Code Online (Sandbox Code Playgroud)

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

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

......并且此函数将由以下值定义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)
Run Code Online (Sandbox Code Playgroud)