【问题标题】:Hiding output from a vectorized function隐藏向量化函数的输出
【发布时间】:2019-08-23 15:28:37
【问题描述】:

背景

在此示例中,我想仅对在提供的环境中找到的对象运行 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")))

该函数正确删除ac,并且在遇到缺少对象的名称时不会发出警告"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

【问题讨论】:

  • 顺便说一句:副作用是有问题的。因此,不要在行尾隐藏语句的副作用,将它们放在开头的显眼位置。含义:不要永远使用-&gt;赋值(除非你坚持,在交互式shell中),因为赋值是副作用。
  • @KonradRudolph 谢谢,我是-&gt; 的粉丝,但我会记住你的建议。

标签: r functional-programming vectorization


【解决方案1】:

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

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

一般来说,以下应该可以解决问题:

vf_fun = function (objects) invisible(Vectorize(fun)(objects))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多