Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify object existence inside a function in R [duplicate]

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"
like image 319
InspectorSands Avatar asked May 26 '16 22:05

InspectorSands


1 Answers

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")

like image 96
Zheyuan Li Avatar answered Nov 12 '22 18:11

Zheyuan Li