作为健全性检查,我希望当下面的函数 seda
中的任何参数是长度大于 1 的向量时,函数就会停止。
问题:不是单独列出所有函数参数(此处为 x
、y
、z
),而是有没有办法使用 match.call
或 formals
等,以便可以立即检查所有函数参数?
我尝试了以下方法但没有成功:
seda <- function(x, y, z){
is.v <- function(...) lengths(list(...)) > 1
if(is.v(match.call())) stop("Error") # instead of `is.v(x, y, z)`
x + y + z
}
seda(2, 2, 3)
seda(c(2, 3), 2, 3)
最佳答案
match.call()
将捕获函数的参数,然后可以测试其长度。我们使用 sapply
返回一个包含每个函数参数长度的向量,并使用 any
函数来测试任何参数的长度是否大于 1。
seda <- function(x, y, z){
if(any(sapply(match.call()[-1], length) > 1)) stop("All arguments must be length 1")
x + y + z
}
seda(2, 2, 3)
[1] 7
seda(c(2, 3), 2, 3)
Error in seda(c(2, 3), 2, 3) : All arguments must be length 1
感谢@erocoar指出可以使用match.call
代替sys.call
并且as.list
是不必要的.
关于r - 在 R 中一次检查所有函数参数长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48123251/