Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
“hasArg”和“exist”之间的区别是什么,用于测试参数是否作为R函数中的输入存在_R_Function_If Statement_Arguments - Fatal编程技术网

“hasArg”和“exist”之间的区别是什么,用于测试参数是否作为R函数中的输入存在

“hasArg”和“exist”之间的区别是什么,用于测试参数是否作为R函数中的输入存在,r,function,if-statement,arguments,R,Function,If Statement,Arguments,我想知道R函数中的hasArg()和exist()之间有什么区别。似乎hasArg()可以工作,而exist无法测试R函数的输入中是否存在参数 f_exists <- function(x){ if(exists("x")){ print("exist") }else{ print("Non existence") }} 但是,如果我在ifelse语句中使用函数hasArg(),该函数可以工作: f_hasArg <- function(x){ if(hasArg(

我想知道R函数中的
hasArg()
exist()
之间有什么区别。似乎
hasArg()
可以工作,而
exist
无法测试R函数的输入中是否存在参数

f_exists <- function(x){
  if(exists("x")){
  print("exist")
}else{
  print("Non existence")
}}
但是,如果我在ifelse语句中使用函数
hasArg()
,该函数可以工作:

f_hasArg <- function(x){
  if(hasArg("x")){
    print("exist")
  }else{
    print("Non existence")
  }
}

> f_hasArg(x = 1)
[1] "exist"
> f_hasArg(x)
[1] "exist"
> f_hasArg()
[1] "Non existence"
我在问为什么
hasArg()
exists()
在R函数和环境中以不同的方式工作?有没有潜在的原因?谢谢。

f_exists()
返回“exist”,因为变量
x
实际上存在于函数
f_exists
中,但它绑定到一个特殊的“缺失”值。使用该值将导致错误(“缺少参数“x”,没有默认值),但由于未使用该值,因此不会报告任何错误

hasArg(“x”)
返回false,因为它实际上查看的是周围函数调用的(形式)参数,而不是当前环境中的任何变量。文档中有更多详细信息:
?exists
?hasArg

要检查调用方是否为函数的形式参数
x
显式提供了值,可以使用
missing(x)
。如果可以通过提供默认参数表达式来实现这一点,那么这样做可能更简单

f_hasArg <- function(x){
  if(hasArg("x")){
    print("exist")
  }else{
    print("Non existence")
  }
}

> f_hasArg(x = 1)
[1] "exist"
> f_hasArg(x)
[1] "exist"
> f_hasArg()
[1] "Non existence"
> rm(list = ls())

> exists("x")
[1] FALSE
> hasArg("x")
[1] FALSE

> x <- 1
> exists("x")
[1] TRUE
> hasArg("x")
[1] FALSE