【发布时间】: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]
- x[2]
有没有办法在函数定义本身中指定这些条件(即约束)?
谢谢
【问题讨论】:
-
不在函数签名中,没有。您需要编写代码来检查函数体中的内容。您可以使用
stopifnot(x1<x2)或stopifnot(all(x<=100 & x>=0))之类的东西,具体取决于您传递的是向量还是单独的值。 -
我建议您阅读 R 中
stopifnot的文档。您可能会在那里找到答案
标签: r function definition date-range