编写一个函数来删除存在的对象 [英] Write a function to remove object if it exists
问题描述
我正试图编写一个函数来删除一个存在的对象。原因是我想摆脱日志消息Error:object'arg'not found。我试过以下内容:
ifrm < - 函数(arg)
{
if(exists( as.character(substitute(arg)))){rm(arg)}
}
不幸的是,如果它存在的话,它不会删除它。
> ifrm < - function(arg)
+ {
+ if(exists(as.character(substitute(arg)))){rm(arg)}
+}
> a< - 2
> ifrm(a)
> a
[1] 2
任何提示我在这里做错了什么?
Best Albrecht
一个普通的习惯用法来抓住用户提供的参数到一个函数是 deparse(substitute(foo))
。这个函数类似于@Ian Ross的函数,但是使用了这个标准的习惯用法:
$ p $ if $ c
if(exists(obj,envir = env)){
rm(list = obj,envir = env)
$ / code $ / pre
我假设你只想删除对象全球环境,因此是默认值,但您可以通过 env
来提供环境。在这里它是在行动:
> a< - 1:10
> ls()
[1]aifrm
> ifrm(a)
> ls()
[1]ifrm
> ifrm(a)
> ls()
[1]ifrm
I am trying to write a function that removes an object if it exists. The reason is that I want to get rid of the log-message Error: object 'arg' not found. I tried the following:
ifrm <- function(arg)
{
if(exists(as.character(substitute(arg)))){rm(arg)}
}
Unfortunately this does not remove the object if it exists
> ifrm <- function(arg)
+ {
+ if(exists(as.character(substitute(arg)))){rm(arg)}
+ }
> a <- 2
> ifrm(a)
> a
[1] 2
Any hints what I do wrong here?
Best Albrecht
A general idiom to grab what the user supplied as an argument to a function is deparse(substitute(foo))
. This function is similar to that of @Ian Ross but employing this standard idiom:
ifrm <- function(obj, env = globalenv()) {
obj <- deparse(substitute(obj))
if(exists(obj, envir = env)) {
rm(list = obj, envir = env)
}
}
where I assume you only ever want to remove objects from the global environment, hence the default, but you can supply an environment via env
. And here it is in action:
> a <- 1:10
> ls()
[1] "a" "ifrm"
> ifrm(a)
> ls()
[1] "ifrm"
> ifrm(a)
> ls()
[1] "ifrm"
这篇关于编写一个函数来删除存在的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!