隐藏向量化函数的输出
Hiding output from a vectorized function
背景
在这个例子中,我想 运行 rm
只对在提供的环境中找到的对象。
可以通过 suppressWarnings
获得类似的结果,但我想使用 Vectorize。
例子
# Create two objects to delete
a <- 1
c <- 2
# b doesn't exist
Vectorize(
FUN = function(object) {
invisible(rm(object))
},
vectorize.args = "object"
) -> vf_rem
# Run function only on existing objects
vf_rem(object = Filter(f = exists, x = c("a", "b", "c")))
该函数正确删除了 a
和 c
并且在遇到名称时不会发出警告缺少对象 "b"
。
问题
vf_rem
仍然输出一个对象到控制台:
>> vf_rem(object = Filter(f = exists, x = c("a", "b", "c")))
$a
NULL
$c
NULL
我想隐藏它,但我已通过 invisible
调用无果而终。
期望的输出
不显示任何内容
>> vf_rem(object = Filter(f = exists, x = c("a", "b", "c")))
>> # Combing back to prompt, nothing is printed
>> # .Last.values contains lst_res from lines below
像其他函数一样反对
>> vf_rem(object = Filter(f = exists, x = c("a", "b", "c"))) -> lst_res
>> lst_res
# Shows list
>> $a
NULL
$c
NULL
在您的特定示例中,您可以使用向量调用 rm
:
vf_rem = function (objects) rm(list = objects)
一般来说,以下应该可以解决问题:
vf_fun = function (objects) invisible(Vectorize(fun)(objects))
背景
在这个例子中,我想 运行 rm
只对在提供的环境中找到的对象。
可以通过 suppressWarnings
获得类似的结果,但我想使用 Vectorize。
例子
# Create two objects to delete
a <- 1
c <- 2
# b doesn't exist
Vectorize(
FUN = function(object) {
invisible(rm(object))
},
vectorize.args = "object"
) -> vf_rem
# Run function only on existing objects
vf_rem(object = Filter(f = exists, x = c("a", "b", "c")))
该函数正确删除了 a
和 c
并且在遇到名称时不会发出警告缺少对象 "b"
。
问题
vf_rem
仍然输出一个对象到控制台:
>> vf_rem(object = Filter(f = exists, x = c("a", "b", "c")))
$a
NULL
$c
NULL
我想隐藏它,但我已通过 invisible
调用无果而终。
期望的输出
不显示任何内容
>> vf_rem(object = Filter(f = exists, x = c("a", "b", "c")))
>> # Combing back to prompt, nothing is printed
>> # .Last.values contains lst_res from lines below
像其他函数一样反对
>> vf_rem(object = Filter(f = exists, x = c("a", "b", "c"))) -> lst_res
>> lst_res
# Shows list
>> $a
NULL
$c
NULL
在您的特定示例中,您可以使用向量调用 rm
:
vf_rem = function (objects) rm(list = objects)
一般来说,以下应该可以解决问题:
vf_fun = function (objects) invisible(Vectorize(fun)(objects))