简体   繁体   中英

R: How to check whether object exists inside function?

Question

I need to check whether an object exists inside a function and not elsewhere. How can I do this?

To make clear what I mean I use exists :

fun <- function(){exists("x")}
x <- 1
fun()
> TRUE

My expected output for the code above is FALSE because the variable x was created outside the function. So x is saved inside the global environment and that is why the funtion returns TRUE but can we somehow test whether x is in "function environment" ?


I've tried

I found this which also does not work in my case. There they suggest using

library(rlang)

f1 <- function(x){ 
  arg <- quo_name(enquo(x))
  if(exists(arg, where = .GlobalEnv)){
    return(2*x)
  } else {
    cat('variable ', '`', arg, '`', ' does not exist', sep = "")
  }
}

I expect the output being variable x does not exist for both following cases but this is not the case if x was defined outside the function before:

x <- 1
f1(x)
> 2

rm(x)
f1(x)
variable `x` does not exist

We can do this by specifying a specific environment for exists to search in and tell it to only look there, and not in the enclosing environments.

The where= argument tells exists where to look for that object. We can either specify it explicitly with environment() (which returns the current environment), or use the default value of -1 which drops the R_GlobalEnv from the list of environments to search.

Either way, the key is to set inherits=FALSE to limit it to only the specified environment. Otherwise, it also looks in the enclosing environments (like R_GlobalEnv ) which we don't want:

x <- 1
fun <- function(){exists("x", inherits = F)}

fun()
[1] FALSE

However if we define x in the enviroment of the function, it returns TRUE:

fun <- function(){
    x<-3;
    exists("x", inherits = F)}
fun()
[1] TRUE

The example mentioned with explicitly defined environment:

fun <- function(){exists("x", where = environment(), inherits = F)}

Another option is to use ls :

f1 <- function() { "x" %in% ls() }

f2 <- function() { x <- 1; "x" %in% ls() }

x <- 1

f1()
#> [1] FALSE
f2()
#> [1] TRUE

Created on 2022-02-04 by the reprex package (v2.0.1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM