【问题标题】:Adding "Conditions" to a Function (R)将“条件”添加到函数 (R)
【发布时间】:2021-09-18 13:44:37
【问题描述】:

我使用 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]

有没有办法在函数定义本身中指定这些条件(即约束)?

谢谢

【问题讨论】:

  • 不在函数签名中,没有。您需要编写代码来检查函数体中的内容。您可以使用 stopifnot(x1&lt;x2)stopifnot(all(x&lt;=100 &amp; x&gt;=0)) 之类的东西,具体取决于您传递的是向量还是单独的值。
  • 我建议您阅读 R 中stopifnot 的文档。您可能会在那里找到答案

标签: r function definition date-range


【解决方案1】:

您可以在函数内部检查所需的条件-

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 1970-01-01
    • 2020-06-07
    相关资源
    最近更新 更多