In R, I’m defining the function lengths depending on the value of a parameter previously set:
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
}
}
Defining a function conditionally in this way seems just a bit… messy. Is there a better way?
You could use
switch:This function provides behavior more like your example code:
…and this function will be defined by the value of
condition: