I am wondering what is the difference between hasArg() and exist() in a R function. It seems that hasArg() works while exist does not work to test if an argument exists in the input of a R function.
f_exists <- function(x){
if(exists("x")){
print("exist")
}else{
print("Non existence")
}}
When I test this f_exists function, the exist seems not to be working in the ifelse statement:
> f_hasArg()
[1] "Non existence"
> f_exists(x)
[1] "exist"
> f_exists()
[1] "exist"
However, if I use the function hasArg() in the ifelse statement, the function works:
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"
However, it is weird that exist() and hasArg() seem to be working in a reversed way when I test them in the environment:
> rm(list = ls())
> exists("x")
[1] FALSE
> hasArg("x")
[1] FALSE
> x <- 1
> exists("x")
[1] TRUE
> hasArg("x")
[1] FALSE
I am asking why is hasArg() and exists() work in a different way in R functions and in the environment? Is there a underlying reason for that? Thanks.
Aucun commentaire:
Enregistrer un commentaire