gpt4 book ai didi

r - 在 R 中的用户定义函数中,如何检查 R 中的输入格式是否正确?

转载 作者:行者123 更新时间:2023-12-04 11:04:05 25 4
gpt4 key购买 nike

如果我的函数有输入 (x,y,z)在 R 中,我想编写一行代码来确保 x 的数据是正确的形式。

x只是一个实数,而不是其他任何东西,例如向量或列表。我假设代码会像

if ( ... ){stop("x must be a real number")}

我想知道括号里面是什么而不是 ... ?

原因是如果我写在一个向量中,程序只是将向量的第一个分量作为输入。 R 会对此发出警告,但我希望该程序立即停止。

最佳答案

如果您想在参数长度为 1 且为实数时“停止”

您可以使用 stopifnot

foo <- function(x, y, z) {
stopifnot(length(x)==1L & is.numeric(x))
}

也许
foo <- function(x, y, z){
if(!(length(x)==1L & is.numeric(x))) { stop("x must be a real number")}
}
stop允许您指定错误消息,而 stopifnot将返回已测试的条件。 (两者各有优势)
stopifnot的好处是它可以准确地告诉您多个条件中的哪一个失败了。例如(注意我现在正在输入多个表达式)
 foo <- function(x, y, z) {
stopifnot(length(x)==1L , is.numeric(x))
}

foo('a')
# Error: is.numeric(x) is not TRUE
foo(c(1,2))
# Error: length(x) == 1L is not TRUE

关于r - 在 R 中的用户定义函数中,如何检查 R 中的输入格式是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26090422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com