我想检查是否在R中定义了一些变量 - 没有出现错误.我怎样才能做到这一点?
我的尝试(不成功):
> is.na(ooxx)
Error: object 'ooxx' not found
> is.finite(ooxx)
Error: object 'ooxx' not found
Run Code Online (Sandbox Code Playgroud)
谢谢!
Dir*_*tel 414
你想要exists()
:
R> exists("somethingUnknown")
[1] FALSE
R> somethingUnknown <- 42
R> exists("somethingUnknown")
[1] TRUE
R>
Run Code Online (Sandbox Code Playgroud)
Rei*_*son 104
有关?exists
"......已定义"的定义,请参阅.例如
> exists("foo")
[1] FALSE
> foo <- 1:10
> exists("foo")
[1] TRUE
Run Code Online (Sandbox Code Playgroud)
tim*_*tim 55
如果你在一个函数中,missing()就是你想要的.
exchequer = function(x) {
if(missing(x)){
message("x is missing… :-(")
}
}
exchequer()
x is missing… :-(
Run Code Online (Sandbox Code Playgroud)
San*_*ich 44
正如其他人所指出的,你正在寻找exists
.请记住,exists
无论您是否定义了变量,使用R的基础包使用的名称都将返回true:
> exists("data")
[1] TRUE
Run Code Online (Sandbox Code Playgroud)
为了解决这个问题(正如Bazz所指出的那样;请参阅参考资料?exists
)inherits
:
> exists("data", inherits = FALSE)
[1] FALSE
foo <- TRUE
> exists("foo", inherits = FALSE)
[1] TRUE
Run Code Online (Sandbox Code Playgroud)
当然,如果你想搜索附加包的名称空间,这也可能不足:
> exists("data.table")
[1] FALSE
require(data.table)
> exists("data.table", inherits = FALSE)
[1] FALSE
> exists("data.table")
[1] TRUE
Run Code Online (Sandbox Code Playgroud)
我唯一能想到的解决方法是 - 在附加包中搜索而不是在基础包中搜索 - 如下:
any(sapply(1:(which(search() == "tools:rstudio") - 1L),
function(pp) exists(_object_name_, where = pp, inherits = FALSE)))
Run Code Online (Sandbox Code Playgroud)
比较替换_object_name_
为"data.table"
(TRUE
)与"var"
(FALSE
)
(当然,如果你不在RStudio,我认为第一个自动附加的环境是"package:stats"
)
Nir*_*mal 25
如果你不想使用引号,你可以使用我在"替换"的示例部分中找到的deparse(substitute())技巧:
is.defined <- function(sym) {
sym <- deparse(substitute(sym))
env <- parent.frame()
exists(sym, env)
}
is.defined(a)
# FALSE
a <- 10
is.defined(a)
# TRUE
Run Code Online (Sandbox Code Playgroud)