gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:28:26 25 4
gpt4 key购买 nike

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
}
}

以这种方式有条件地定义一个函数似乎有点……困惑。有没有更好的办法?

最佳答案

您可以使用 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)

关于r - 使用 if-else 语句有条件地定义 `R` 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9996077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com