stats_noob
stats_noob

Reputation: 5925

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:

BUT

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

Thanks

Upvotes: 0

Views: 1191

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389175

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

Upvotes: 3

Related Questions