Verify object existence inside a function in R [du

2020-02-12 07:09发布

I want to determine whether an object exists inside a function in R:

foo <- function() {
 y <- "hello" 
 if (exists(y, envir = sys.frame())) print(y)
}
foo()

Error in exists(y, envir = sys.frame()) : invalid first argument

I thought adding the envir = sys.frame() would do the trick. Also tried envir = environment()

Expected

foo()
"hello"

1条回答
劳资没心,怎么记你
2楼-- · 2020-02-12 07:55

You should have checked ?exists:

Usage:

     exists(x, where = -1, envir = , frame, mode = "any",
            inherits = TRUE)

Arguments:

       x: a variable name (given as a character string).

Do exists("y")

查看更多
登录 后发表回答