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
:
lengths <- function(vector, condition) {
switch(condition,
ceiling(length(vector)/2),
length(vector),
length(vector)*2,
length(vector)*+10)
}
This function provides behavior more like your example code:
lengths <- function(vector, condition) {
switch(as.character(condition),
`1`=ceiling(length(vector)/2),
`2`=length(vector),
`3`=length(vector)*2,
length(vector)*+10)
}
...and this function will be defined by the value of 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With