将 "Conditions" 添加到函数 (R)
Adding "Conditions" to a Function (R)
我使用的是 R 编程语言。
假设您有一个接受 4 个输入并对这些输入求和的函数:
# first way to write this:
my_function_a <- function(x) {
final_value = x[1] + x[2] + x[3] + x[4]
}
或者可以这样写:
# 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
}
假设我想添加一些限制这些输入范围的条件。例如:
- [x1]、[x2]、[x3]、[x4] 只能在“0 到 100”之间
但是
- x[1] < x[2]
- x[2] < x[4]
有没有办法在函数定义本身中指定这些条件(即约束)?
谢谢
您可以在函数内部检查所需的条件-
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
我使用的是 R 编程语言。
假设您有一个接受 4 个输入并对这些输入求和的函数:
# first way to write this:
my_function_a <- function(x) {
final_value = x[1] + x[2] + x[3] + x[4]
}
或者可以这样写:
# 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
}
假设我想添加一些限制这些输入范围的条件。例如:
- [x1]、[x2]、[x3]、[x4] 只能在“0 到 100”之间
但是
- x[1] < x[2]
- x[2] < x[4]
有没有办法在函数定义本身中指定这些条件(即约束)?
谢谢
您可以在函数内部检查所需的条件-
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