Search code examples
rfunctiondefinitiondate-range

Adding "Conditions" to a Function (R)


I using the R programming language.

Suppose you have a function that takes 4 inputs and sums these inputs :

# first way to write this:

my_function_a <- function(x) {
  
  final_value = x[1] + x[2] + x[3] + x[4]
  
 
}

Or can be written another way:

# second way way to write this:

my_function_b <- function(input_1, input_2, input_3, input_4) {

final_value = input_1+ input_2+ input_3+ input_4
 
}

Suppose I want to add some conditions which restrict the ranges of these inputs. For example:

  • [x1] , [x2], [x3], [x4] can only be between "0 and 100"

BUT

  • x[1] < x[2]
  • x[2] < x[4]

Is there a way to specify these conditions (i.e. constraints) within the function definition itself?

Thanks


Solution

  • You can check for the required conditions inside the function -

    my_function_a <- function(x) {
      final_value <- NULL
      if(all(x > 0 & x < 100) &&  x[1] < x[2] && x[2] < x[4]){
        final_value = x[1] + x[2] + x[3] + x[4]  
      }
      return(final_value)
    }
    
    my_function_a(c(10, 20, 30, 40))
    #[1] 100
    
    my_function_a(c(10, 20, 30, 400))
    #NULL
    
    my_function_a(c(10, 20, 30, 10))
    #NULL