验证R中的函数内是否存在对象[重复]

时间:2021-08-08 23:22:25

This question already has an answer here:

这个问题在这里已有答案:

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

我想确定一个对象是否存在于R中的函数内:

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

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

存在错误(y,envir = sys.frame()):第一个参数无效

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

我以为添加envir = sys.frame()就可以了。还试过envir = environment()

Expected

预期

foo()
"hello"

1 个解决方案

#1


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

存在(“y”)

#1


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

存在(“y”)