dplanet
dplanet

Reputation: 5403

Using an if-else statement to conditionally define a function in `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?

Upvotes: 7

Views: 2029

Answers (2)

Carl Witthoft
Carl Witthoft

Reputation: 21502

A quick hack based on CSGillespie's suggestion:

length.lut  <-  cbind(c(0.5,1,2,1,),c(0,0,0,10))

lengths <- function(vector, condition) vector*length.lut[condition,1] + length.lut[condition,2] 

Upvotes: 0

Joshua Ulrich
Joshua Ulrich

Reputation: 176648

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)

Upvotes: 9

Related Questions