Verify object existence inside a function in R [duplicate]

本小妞迷上赌 提交于 2019-11-28 04:27:17

问题


This question already has an answer here:

  • How to check if object (variable) is defined in R? 6 answers

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:


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



来源:https://stackoverflow.com/questions/37471992/verify-object-existence-inside-a-function-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!