如何检查 R 函数的输入参数是否存在 [英] How to check existence of an input argument for R functions
本文介绍了如何检查 R 函数的输入参数是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数定义为
myFun <- function(x, y, ...) {
# using exists
if (exists("z")) { print("exists z!") }
# using missing
try(if (!missing("z")) { print("z is not missing!") }, silent = TRUE)
# using get
try(if (get("z")) { print("get z!") }, silent = TRUE)
# anotherFun(...)
}
在这个函数中,我想检查用户是否在参数列表中输入了z".我怎样才能做到这一点?我尝试了 exists("z")
、missing("z")
和 get("z")
,但它们都不起作用.
In this function, I want to check whether user input "z" in the argument list. How can I do that? I tried exists("z")
, missing("z")
, and get("z")
and none of them works.
推荐答案
@Sacha Epskamp 有一个很好的解决方案,但它并不总是有效.失败的情况是如果z"参数作为 NULL 传入...
@Sacha Epskamp has a pretty good solution, but it doesn't always work. The case where it fails is if the "z" argument is passed in as NULL...
# Sacha's solution
myFun <- function(x, y, ...) {
args <- list(...)
exist <- !is.null(args[['z']])
return(exist)
}
myFun(x=3, z=NULL) # FALSE, but should be TRUE!
# My variant
myFun2 <- function(x, y, ...) {
args <- list(...)
exist <- "z" %in% names(args)
exist
}
myFun2(x=3, z=NULL) # TRUE
这篇关于如何检查 R 函数的输入参数是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文