隐藏矢量化函数的输出

时间:2019-04-02 10:26:26

标签: r functional-programming vectorization

背景

在此示例中,我只想在提供的环境中找到的对象上运行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 ,并且在遇到丢失的对象 {{1 }}

问题

"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

1 个答案:

答案 0 :(得分:2)

在您的特定示例中,您可以使用向量调用rm

vf_rem = function (objects) rm(list = objects)

通常,以下方法可以解决问题:

vf_fun = function (objects) invisible(Vectorize(fun)(objects))
相关问题