Verify object existence inside a function in R [duplicate]
Asked Answered
C

1

7

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"
Compelling answered 26/5, 2016 at 22:21 Comment(1)
Use missing() e.g. https://mcmap.net/q/92279/-how-to-check-if-object-variable-is-defined-in-rMaffick
M
5

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

Myalgia answered 26/5, 2016 at 22:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.