Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an if-else statement to conditionally define a function in `R`

Tags:

r

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?

like image 538
dplanet Avatar asked Apr 03 '12 15:04

dplanet


1 Answers

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)
like image 169
Joshua Ulrich Avatar answered Nov 14 '22 22:11

Joshua Ulrich